【发布时间】:2013-07-02 23:16:27
【问题描述】:
下面的 XPath 查询使用 Google 文档的 importXML 可以正常工作,但不能使用以下 PHP 脚本。如果我将查询更改为更简单的查询,脚本将按预期工作。很长一段时间以来,我一直在尝试解决此问题,如果有任何建议,我将不胜感激。
非常感谢!
$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.txtoutput
N/A,
N/A,
N/A,
N/A,
N/A,
有效的 XPath 查询
//a
【问题讨论】:
-
请将您的示例缩减为能够产生错误的 single HTML 文档(片段)(以便可以复制示例,这通常是 SO 所必需的) .接下来是您还应该添加有效的 xpath 查询。