2011-09-03 5 views
1

변경할 수없는 형식이 잘못된 HTML이 있습니다. 의 XPath 쿼리를 실행하면 전혀 노드를 반환하지 않습니다형식이 잘못된 HTML 및 XPath 쿼리

$el = $xpath->query("//a[@class='product']/table"); // can get a tag with "//a[@class='product']" 
print_r($el->length); // 0 

잘못된 HTML :

<a class="product" href="#"> 
    <table width="385" cellspacing="0" cellpadding="5" style="border:1px; border-bottom-color:#E2E2E2; border-bottom-style:solid;"> 
     <tr> 
      <td width="55"> 
       <img src="http://foobar.com:8080/img/1212.jpg" height="50" width="50"> 
      </td> 
     <td width="195">Cod.27731<br>Product Name</td> 
      <td width="60" align="center"><a href="?pageContent=items&price=fab&prodcod=27731">Details</a></td> 
      <td width="80" nowrap> 
       <div style="color:#FF0000;"><strong>$ 35.23</strong></div> 
     </td> 
     </tr> 
    </table> 
</a> 

내가이 (가) 요소를 얻을 수 있습니다하지만 난 그 자식 (테이블)를 얻을 수 없다 ..

+1

'$ 문서 수준> saveHTML()'당신은 알 수 있다는 그 DOMDocument를 자동 -앞에 '' 태그를 닫습니다. – arnaud576875

+0

HTML()이 잘못된 HTML을 저장합니까? – thom

+1

'loadHTML()'이 이미 잘못된 HTML을 고치고 있다고 생각합니다. (이 경우 태그를 닫음으로써) – arnaud576875

답변

0

libxml이 테이블 앞에있는 요소를 닫기 위해 HTML을 변경하므로 대신 following-sibling 테이블을 쿼리해야합니다. 당신이 경우에 a 요소에서 통과

$dom = new DOMDocument; 
$dom->loadHtml($html); 
$xpath = new DOMXpath($dom); 
$el = $xpath->query("//a[@class='product']/following-sibling::table"); 
echo $dom->saveHtml($el->item(0)); 

또는

$dom = new DOMDocument; 
$dom->loadHtml($html); 
$xpath = new DOMXpath($dom); 
$table = $xpath->query("//a[@class='product']")->item(0)->nextSibling; 
echo $dom->saveHtml($table); 

주 saveHTML requires at least PHP 5.3.6에 인수를 전달하는 것은

+0

HTML을로드 할 때, 맞습니까? 단지 saveHTML을 할 때뿐만 아니라 ... – thom

+0

@thom 네,'loadHTML'을 사용할 때 [libxml] (http://xmlsoft.org/html/libxml-HTMLparser.html)는 'saveHTML()'은 DOM 트리를 HTML 마크 업으로 직렬화 할뿐, [tidy] (http://php.net/tidy)를 통해 깨진 HTML을 실행하는 것입니다. DOM에 전달하기 전에이 방법을 사용하면 깨진 마크 업이 어느 정도 수정 될 수 있습니다. – Gordon

+1

고맙습니다! 문제가 해결되었습니다! – thom