我遇到了上述错误,并尝试打印出对象以查看我如何访问其中的数据,但它只回显DOMNodeList Object()
function dom() {
$url = "http://website.com/demo/try.html";
$contents = wp_remote_fopen($url);
$dom = new DOMDocument();
@$dom->loadHTML($contents);
$xpath = new DOMXPath($dom);
$result = $xpath->evaluate('/html/body/table[0]');
print_r($result);
}
我正在使用Wordpress,因此解释了wp_remote_fopen函数。我正试图从$ url
回显第一个表答案 0 :(得分:15)
是的,DOMXpath::query
返回始终是DOMNodeList
,这是一个奇怪的对象需要处理。您基本上必须迭代它,或者只使用item()
来获取单个项目:
// There's actually something in the list
if($result->length > 0) {
$node = $result->item(0);
echo "{$node->nodeName} - {$node->nodeValue}";
}
else {
// empty result set
}
或者你可以遍历这些值:
foreach($result as $node) {
echo "{$node->nodeName} - {$node->nodeValue}";
// or you can just print out the the XML:
// $dom->saveXML($node);
}
答案 1 :(得分:0)
Xpath以1而不是0开始索引:/html/body/table[1]
现在,这取决于您是要保存匹配节点的HTML还是要保存节点的文本内容。
$html = <<<'HTML'
<html>
<body>
<p>Hello World</p>
</body>
</html>
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
// iterate all matched nodes and save them as HTML to a buffer
$result = '';
foreach ($xpath->evaluate('/html/body/p[1]') as $p) {
$result .= $dom->saveHtml($p);
}
var_dump($result);
// cast the first matched node to a string
var_dump(
$xpath->evaluate('string(/html/body/p[1])')
);
string(18) "<p>Hello World</p>"
string(11) "Hello World"