Xpath 在解析基本 html 时不适合我 [英] Xpath not behaving for me in parsing basic html
本文介绍了Xpath 在解析基本 html 时不适合我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 xpath 解析一些基本的 html 并遇到问题.使用我正在阅读的 xpath 文档所说的工作,返回的输出始终为空.下面是我第一次尝试做这项工作.一如既往地感谢任何帮助.
I am trying to parse some basic html using xpath and running into issues. The returned output is always empty using what I am reading the xpath docs to say works. Below is my first attempt at making this work. Any help is appreciated as always guys and gals.
$html = '<ul>';
$html .= ' <li id="stuff-12345"> some content here </li>';
$html .= ' <li id="stuff-54321"> some other content here </li>';
$html .= '</ul>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$result = $xpath->query('//ul/li');
foreach($result as $e){
echo $e->item(0)->nodeValue . "\n";
}
推荐答案
DOMXPath::query
返回一个 DOMNodeList
.当你在做
DOMXPath::query
returns a DOMNodeList
. When you are doing
foreach($result as $e){
您正在遍历 DOMElement
项和 DOMNodeList
.DOMElement
没有 item()
方法.只有 DOMNodeList
有.试试
you are iterating over the DOMElement
items a DOMNodeList
. DOMElement
does not have an item()
method. Only DOMNodeList
has that. Try with
foreach($result as $e){
echo $e->nodeValue, PHP_EOL;
}
这篇关于Xpath 在解析基本 html 时不适合我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文