我正在尝试使用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遍历所有结果,我要做的就是从
$node
中的foreach
中提取链接和文本,但是由于$node
本身是一个对象,因此我无法从中创建DOMDocument
。我该如何查询?
最佳答案
首先,您的XPath表达式尝试匹配不存在的href
子元素,并在@href
中查询属性。
您无需创建任何新的DOMDocument
,只需将$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);
}
关于php - 如何在PHP中使用XPath查询DOMNode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831157/