如何解决无法将类DOMNodeList的对象转换为字符串
| 我收到上述错误,并尝试打印出该对象,以查看如何访问其中的数据,但它仅回显DOMNodeList对象()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回显第一个表
解决方法
是的,返回
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);
}
,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])\')
);
演示:https://eval.in/155592
string(18) \"<p>Hello World</p>\"
string(11) \"Hello World\"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。