双Xpath与PHP无法正常工作

时间:2011-05-27 13:08:29

标签: php xpath

我正在使用php并通过URL成功加载了HTML-Document。现在我也成功处理了一个frist XPath,但我在同一个DOMDocument()上的第二个似乎总是失败,没有错误但只有没有结果。是我的代码还是我遗漏的任何其他东西(我试图从Apple的App-Store网站上测试信息,实际上是指定应用程序的描述:

//retrieving description
$path2 = "//div[@class='product-review'][1]/p[@class='truncate']";
$result_row = $xpath->query($path2);
print_r($result_row);
foreach($result_row as $rows){
  echo "haben was";
  print_r($rows);
  $desc = $rows->childNodes->item(0)->textContent();
}

2 个答案:

答案 0 :(得分:0)

AppStore by using the public API

的客户评论外,您几乎可以获得所有内容
$appStore = json_decode(
    file_get_contents(
        'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=387851294'
    )
);
echo $appStore->results[0]->description;

Example of full Json Result

答案 1 :(得分:0)

这似乎是命名空间问题。您的示例HTML源代码以

开头
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.apple.com/itms/" lang="de">

xmlns表示文档具有默认命名空间,因此所有XPath查询都需要引用该命名空间才能找到任何元素。 (有趣的是,他们在doctype中声称这是一个XHTML文档,但他们未能在XHTML命名空间中设置它。)

您需要注册<html>使用的默认命名空间。因为<html>在默认命名空间中,所以它没有任何前缀,但为了使XPath能够工作,您还需要将此命名空间绑定到某个前缀,然后在XPath表达式中使用该前缀。

$your_xml_doc->registerXPathNamespace("ns", "http://www.apple.com/itms/");
$path2 = "//ns:div[@class='product-review'][1]/ns:p[@class='truncate']";

没有名称空间前缀的XPath(1.0)表达式始终只与no-namespace中的目标匹配。

相关问题