php domdocument获取节点信息

时间:2017-10-21 14:35:54

标签: php domdocument

我正在使用php,我正在尝试从网页获取某些数据

一切顺利,直到我到达这一部分:

<a class="cleanthis" href="https://www.web.com" id="1122" rel="#1122" style="display: inline-block;"><strong>the data i want</strong></a>

正如你所看到的,我希望数据很强,但我无法得到它。我只得到空行

我使用的代码:

foreach($as as $a) {
        if ($a->getAttribute('class') === 'cleanthis') {


$strong =  $a->getElementsByTagName('strong');
echo $strong->nodeValue;;

}

1 个答案:

答案 0 :(得分:0)

您应该看到以下错误消息:

  

未定义属性:DOMNodeList :: $ nodeValue

这是因为$strong = $a->getElementsByTagName('strong');会将DOMNodeList放入$string。您需要迭代列表或从中检索实际节点,例如

echo $strong->item(0)->nodeValue;

或者你可以使用XPath:

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->evaluate('//a[@class="cleanthis"]/strong/text()') as $element) {
    echo $element->nodeValue, PHP_EOL;
}