对象无法转换为字符串
问题描述:
我得到了上面的错误,并试图打印出对象,看我怎么可以访问它里面的数据,但它只是呼应的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])')
);
string(18) "<p>Hello World</p>"
string(11) "Hello World"
谢谢,真正帮助我的理解! – Ryan 2011-05-26 17:19:29