2010-05-17 5 views
0

지난 밤의 비슷한 질문으로 소스 HTML을 수정할 권한이 없으며 제품 가격/비교를 위해 웹 사이트에서 많은 데이터를 구문 분석하려고합니다. 대부분의 경우 작동하지만, 이제는 더 효율적이고 빠르고 쉽게 스파게티 코드를 읽을 수 있도록 노력하고 있습니다.PHP Xpath, 매우 구체적인 노드를 선택하는 데 도움이

다음 테스트 코드가 있습니다. 내가하고 싶은 일은 인 경우 콘텐츠의 속성 (예 : thisiswhatiwant) 만 반환합니다. productType의 nodeValue는 주식이며 다른 것은 아무것도 아닙니다.

<div id="productListing"> 

<div class="productDetail"> 
    <span class="productType">Stocked</span>: <span class="productStock"><span class='productContent' content='thisiswhatiwant'></span></span> 
</div> 

<div class="productDetail"> 
    <span class="productType">Non-stocked</span>: <span class="productStock"><span class='productContent' content='xyz'></span></span> 
</div> 

… 

<div class="productDetail"> 
    <span class="productType">Non-stocked</span>: <span class="productStock"><span class='productContent' content='123'></span></span> 
</div> 

</div> 

이것은 내가 지금까지 가지고있는 Xpath 쿼리이지만 중요한 것 또는 내 머리 속의 무언가를 놓치고 있습니다. 아직 기어를 클릭하지 않았습니다.

//div[@id="productListing"]/div[@class="productDetail"]/span[@class="productStock"]/preceding-sibling::span[text()="Stocked"] 

는 기본적으로, 내가 위의 테스트 코드에서 출력하고자하는 것입니다 :

<? 
echo "Output: " . $dom->getAttribute('content'); 
?> 

Output: thisiswhatiwant 

누구나 어떤 아이디어를 가지고?

답변

2

Assumig $dom 지정된 XML 문자열에서 만든있는 DOMDocument 객체이다 : 그것을했다

$xpath = new DOMXPath($dom); 
$q = '//span[@class="productType" and text()="Stocked"]/ancestor::*[@class="productDetail"]/span[@class="productStock"]/span[@class="productContent"]'; 
$res = $xpath->query($q); 
foreach($res as $node) { 
    echo $node->getAttribute('content') . PHP_EOL; 
} 
+0

가! 고맙습니다. –

관련 문제