PHP 中带有 html5lib 的 Xpath

Zna*_*kus 4 html php xpath html5lib

我有这个不起作用的基本代码。如何在 html5lib php 中使用 Xpath?或以任何其他方式使用 HTML5 的 Xpath。

$url = 'http://en.wikipedia.org/wiki/PHP';
$response = GuzzleHttp\get($url);

$html5 = new Masterminds\HTML5();
$dom = $html5->loadHTML($response);

$xpath = new DOMXPath($dom);

$elements = $xpath->query('//h1');
//$elements = $dom->getElementsByTagName('h1');

foreach ($elements as $element)
{
    var_dump($element);
}
Run Code Online (Sandbox Code Playgroud)

未找到任何元素。使用$xpath->query('.')作品来获取根元素(通常 xpath 似乎有效)。$dom->getElementsByTagName('h1')正在工作。

sou*_*011 5

使用disable_html_ns选项。

$url = 'http://en.wikipedia.org/wiki/PHP';
$response = GuzzleHttp\get($url)->getBody();
$html5 = new Masterminds\HTML5(array(
    'disable_html_ns' => true, // add `disable_html_ns` option
));
$dom = $html5->loadHTML($response);

$xpath = new DOMXPath($dom);
$elements = $xpath->query('//h1');

foreach ($elements as $element) {
    var_dump($element);
}
Run Code Online (Sandbox Code Playgroud)

https://github.com/Masterminds/html5-php#options

disable_html_ns(boolean):防止解析器自动将 HTML5 命名空间分配给 DOM 文档。这适用于非命名空间感知 DOM 工具。