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.
Many thanks in advance!
$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);
}
Script description.txt
output
N/A,
N/A,
N/A,
N/A,
N/A,
XPath query that works
//a