繁体   English   中英

php domdocument获取节点信息

[英]php domdocument get node info

我正在使用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;;

}

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

未定义的属性: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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM