问题描述
下面的 XPath 查询使用 Google 文档的 importXML 可以正常工作,但不能使用以下 PHP 脚本.如果我将查询更改为更简单的查询,脚本将按预期工作.我已经尝试解决这个问题一段时间了,如果您有任何建议,我将不胜感激.
The XPath query below works perfectly fine using Google docs' importXML but not working using the following PHP script. If I change the query to one that is more simple, the script works as expected. I have been trying to troubleshoot this problem for quite a while and would appreciate any suggestions.
非常感谢!
$file = fopen('info-urls.txt', "r");
$output = array();
$i=1;
while(!feof($file)){
$line = fgets($file);
echo $line . '<br/>';
$doc = new DOMDocument();
$doc->loadHTMLFile(trim($line));
$xpath = new DOMXpath($doc);
$elements = $xpath->query("substring((//*[self::div or self::p or self::li or self::td or self::tr or self::table or self::h4 or self::h4 or self::h3 or self::h2 or self::h1][contains(text(),'boat') or contains(text(),'bike') or contains(text(),'car')]/text())[1], 0, 499)");
if ($elements->length == 0) {
$output[] = 'N/A';
}else{
foreach ($elements as $element) {
$nodes = $element->childNodes;
foreach ($nodes as $node) {
if(strcmp($node->nodeValue, "")!=0){
$output[] = trim($node->nodeValue);
}
}
}
}
}
array2csv($output);
print_r($output);
function array2csv(array &$array){
$file = 'descriptions.txt';
$csvFormat = "";
for($i=0; $i < sizeof($array); $i++){
$csvFormat .= $array[$i] . ",\n";
}
file_put_contents($file, $csvFormat);
}
脚本description.txt
输出
N/A,
N/A,
N/A,
N/A,
N/A,
有效的 XPath 查询
XPath query that works
//a
推荐答案
使用 $xpath->evaluate()
而不是 $xpath->query()
.这是因为您的查询将返回标量字符串而不是 DOMNodeList
,它将返回 XPath 函数 substring()
的结果,实际上是一个字符串.
Use $xpath->evaluate()
instead of $xpath->query()
. This is because your query will return a scalar string rather than a DOMNodeList
, it will return the result of the XPath function substring()
what is actually a string.
这篇关于相同的 XPath 查询适用于 Google 文档,但不适用于 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!