[英]php domdocument get node info
I am working with php and I am trying to get certain data from a webpage 我正在使用php,正在尝试从网页中获取某些数据
everything works till i get to this part: 一切正常,直到我进入这一部分:
<a class="cleanthis" href="https://www.web.com" id="1122" rel="#1122" style="display: inline-block;"><strong>the data i want</strong></a>
As you can see i want the data in strong but i cant get it. 如您所见,我想要强大的数据,但我无法获取。 I only get blank lines 我只有空白行
code i use: 我使用的代码:
foreach($as as $a) {
if ($a->getAttribute('class') === 'cleanthis') {
$strong = $a->getElementsByTagName('strong');
echo $strong->nodeValue;;
}
You should be seeing this error message: 您应该会看到以下错误消息:
Undefined property: DOMNodeList::$nodeValue 未定义的属性:DOMNodeList :: $ nodeValue
That is because $strong = $a->getElementsByTagName('strong');
那是因为$strong = $a->getElementsByTagName('strong');
will put a DOMNodeList
in $string
. 会将DOMNodeList
放在$string
。 You either need to iterate the list or retrieve the actual node from it, eg 您需要迭代列表或从列表中检索实际节点,例如
echo $strong->item(0)->nodeValue;
Or you can just use XPath: 或者,您可以只使用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.