Return xpath Dom 解析的所有结果?

Return all results from xpath Dom parse?

我想使用 PHP 抓取一个网站, 这是代码:

<?php  
$url = 'http://sample.com';
$dom = new DOMDocument();
@$dom->loadHTMLFile($url);
$xpath = new DOMXpath($dom);
$contents = $xpath->query('//p[@class="ac"]');
$content = $dom->saveHTML($contents->item(0));
echo $content;
echo '<br />';
 ?>

但它会 return 只有第一个具有 "ac" class 的 p 标签,但我希望它 return 所有结果。所以我将代码编辑为:

<?php  
$url = 'http://sample.com';
$dom = new DOMDocument();
@$dom->loadHTMLFile($url);
$xpath = new DOMXpath($dom);
$contents = $xpath->query('//p[@class="ac"]');
$content = $dom->saveHTML($contents->item(0));
for($i=0;$i<$contents->length; $i++){
    echo $contents->item($i);
}
echo '<br />';
 ?>

但是,它给了我这个错误:

Catchable fatal error: Object of class DOMElement could not be converted to string in

我做错了什么?

$contents->item($i) 是 DomElement 对象。例如,您可以打印 $contents->item($i)->nodeValue 来获取段落文本,或者以这种方式 $content = $dom->saveHTML($contents->item($i)) 来获取 outerhtml。

但我更喜欢这样的循环

$xpath = new DOMXpath($dom);
foreach($xpath->query('//p[@class="ac"]') as $content) 
   echo  $dom->saveHTML($content);
echo '<br />';