如何在PHP中使用XPath查询DOMNode?

如何在PHP中使用XPath查询DOMNode?,php,xpath,bing,Php,Xpath,Bing,我正在尝试使用XPath获取bing搜索结果。这是我的密码: $html = file_get_contents("http://www.bing.com/search?q=bacon&first=11"); $doc = new DOMDocument(); libxml_use_internal_errors(true); $doc->loadHtml($html); $x = new DOMXpath($doc); $output = array(); // just gra

我正在尝试使用XPath获取bing搜索结果。这是我的密码:

$html = file_get_contents("http://www.bing.com/search?q=bacon&first=11");
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHtml($html);
$x = new DOMXpath($doc);
$output = array();
// just grab the urls for now
foreach ($x->query("//li[@class='b_algo']") as $node)
{
    //$output[] = $node->getAttribute("href");
    $tmpDom = new DOMDocument();
    $tmpDom->loadHTML($node);
    $tmpDP = new DOMXPath($tmpDom);
    echo $tmpDP->query("//div[@class='b_title']//h2//a//href");
}
return $output;

这个foreach迭代所有结果,我只想从
foreach
中的
$node
提取链接和文本,但是因为
$node
本身是一个对象,所以我无法从中创建
DOMDocument
。如何查询它?

首先,您的XPath表达式尝试匹配不存在的
href
子元素,查询属性的
@href

您不需要创建任何新的
DOMDocument
s,只需将
$node
作为上下文项传递:

foreach ($x->query("//li[@class='b_algo']") as $node)
{
    var_dump( $x->query("./div[@class='b_title']//h2//a//@href", $node)->item(0) );       
}   
如果您对URL感兴趣,也可以直接查询:

foreach ($x->query("//li[@class='b_algo']/div[@class='b_title']/h2/a/@href") as $node)    
{
  var_dump($node);
}

为什么不
//li[@class='b_-algo']//div[@class='b_-title']//h2//a//href
?试试上面提到的@splash58。必须工作。这里没有使用XQuery,PHP甚至不支持它。请不要垃圾邮件无关的标签。