简体   繁体   中英

DOMXPath not working

I am trying to get the price of products in a webshop but DOMXPath doest seem to be working.

The server is running php 5.5 and LibXML is enabled. No errors are returned, only a length of zero.

 ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
session_start();

$xmlsource = 'https://tennistoko.nl/product/professional-supreme-comfort-grip-3-st';

$d = new DOMDocument();
$d->loadHTML($xmlsource);
$xpath = new DOMXPath($d);




$nodes = $xpath->query('//*[@itemprop]');  //this catches all elements with itemprop attribute
foreach ($nodes as $node) { 
   // do your stuff here with $node
   print_r($node);
}    


print_r($nodes);

loadHTML is for loading HTML from a string, to load from file or url use loadHTMLFile .

$xmlsource = 'https://tennistoko.nl/product/professional-supreme-comfort-grip-3-st';

$d = new DOMDocument();
@$d->loadHTMLFile($xmlsource);      // @ if for suppressing warnings
$xpath = new DOMXPath($d);

$nodes = $xpath->query('//*[@itemprop]');  //this catches all elements with itemprop attribute
foreach ($nodes as $node) { 
   // do your stuff here with $node
   print_r($node);
} 

Try adding / at the end of the url otherwise the document is empty and use loadHTMLFile as Danijel suggested:

$xmlsource = 'https://tennistoko.nl/product/professional-supreme-comfort-grip-3-st/';//changed your code here
$d = new DOMDocument();
@$d->loadHTMLFile($xmlsource);      // @ if for suppressing warnings
$xpath = new DOMXPath($d);
$nodes = $xpath->query('//*[@itemprop]');  //this catches all elements with   itemprop attribute
foreach ($nodes as $node) { 
  // do your stuff here with $node
  print_r($node);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM