DOMXPath 不工作

DOMXPath not working

我正在尝试获取网上商店的产品价格,但 DOMXPath 似乎没有用。

服务器是 运行 php 5.5 并且启用了 LibXML。没有返回错误,只有长度为零。

 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);
} 

尝试在 url 的末尾添加 / 否则文档为空并按照 Danijel 的建议使用 loadHTMLFile:

$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);
}