格式错误的HTML和XPath查询

时间:2011-09-03 19:45:49

标签: php html dom xpath malformed

我的格式错误,我无法改变。运行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 个答案:

答案 0 :(得分:0)

由于libxml将更改HTML以关闭表之前的a元素,因此您必须查询following-sibling表,例如。

$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));

或遍历a元素

$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