解析html文档,但比较文本内容时出现问题


parsing html doc but issue with comparing text content

我使用PHP检索文档并在HTML中查找一些数据。

我使用了Tidy clean and repair,因为文档中包含很多糟糕的html。

不管怎样,

在html文档中有一个标签,类似于:

<a href="www.google.com">Link 12345</a>

如果文本内容(链接12345)与某个字符串匹配,我想获得属性(www.google.com)的值。

$h2 = $doc->getElementsByTagName('a');
for ($i2; $i2 < $h2->length; $i2++) {
    $attr2 = $h2->item($i2)->getAttribute('href');

    if ($h2->item($i2)->textContent == "Link 12345")
        print "FOUND";
}

这似乎不起作用。我知道for循环在某个时刻(当调用->textContent时)返回"链接12345"。但是,即使打印出链接12345,比较也总是失败。我怀疑编码有问题,但我无法修复。

谢谢。

您可以使用PHP的DOMXPath对DOM对象执行XPath查询。

我相信对你来说,这将是

//a[text()="Link 12345"]

将返回所有谁的文本是"链接12345"。

一个简单的错误:您正在测试"$h2->item($i2)->textContent"而不是"$h2->textContent"

不是吗?