2010-07-06 9 views
3

html 파일을 구문 분석하려고합니다.php xpath : 쿼리 결과 내의 쿼리

titledesc 클래스로 스팬을 가져오고 class = 'thebest'속성이있는 각 div에서 정보를 가져 오는 것이 좋습니다.

<?php 

$example=<<<KFIR 
<html> 
<head> 
<title>test</title> 
</head> 
<body> 
<div class="a">moshe1 
<div class="aa">haim</div> 
</div> 
<div class="a">moshe2</div> 
<div class="b">moshe3</div> 

<div class="thebest"> 
<span class="title">title1</span> 
<span class="desc">desc1</span> 
</div> 
<div class="thebest"> 
span class="title">title2</span> 
<span class="desc">desc2</span> 
</div> 

</body> 
</html> 
KFIR; 


$doc = new DOMDocument(); 
@$doc->loadHTML($example); 
$xpath = new DOMXPath($doc); 
$expression="//div[@class='thebest']"; 
$arts = $xpath->query($expression); 

foreach ($arts as $art) { 
    $arts2=$xpath->query("//span[@class='title']",$art); 
    echo $arts2->item(0)->nodeValue; 
    $arts2=$xpath->query("//span[@class='desc']",$art); 
    echo $arts2->item(0)->nodeValue; 
} 
echo "done"; 

예상되는 결과는 다음과 같습니다 : I 받고있어

title1desc1title2desc2done 

결과는 다음과 같습니다 여기

내 코드입니다

title1desc1title1desc1done 

답변

10

검색어를 상대적으로 만드십시오 ... 점으로 시작하십시오 (예 : ".//…").

foreach ($arts as $art) { 
    // Note: single slash (direct child) 
    $titles = $xpath->query("./span[@class='title']", $art); 
    if ($titles->length > 0) { 
     $title = $titles->item(0)->nodeValue; 
     echo $title; 
    } 

    $descs = $xpath->query("./span[@class='desc']", $art); 
    if ($descs->length > 0) { 
     $desc = $descs->item(0)->nodeValue; 
     echo $desc; 
    } 
} 
1

대신 두 번째 쿼리를 수행하는 시도해보십시오 textContent

textContent은이 노드와 그 하위 노드의 텍스트 내용을 반환합니다.

대안으로 thebest 제목 또는 내림차순의 클래스를 갖는 클래스 div의 스팬 자녀 가져올 것이다 즉

$expression="//div[@class='thebest']/span[@class='title' or @class='desc']"; 
$arts = $xpath->query($expression); 

foreach ($arts as $art) { 
    echo $art->nodeValue; 
} 

에 XPath를 변경.