gpt4 book ai didi

php - 在 PHP 中使用 html5lib 的 Xpath

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:08:25 24 4
gpt4 key购买 nike

我有这个不起作用的基本代码。如何将 Xpath 与 html5lib php 一起使用?或以任何其他方式使用 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);
}

没有找到元素。使用 $xpath->query('.') 用于获取根元素(xpath 通常似乎有效)。 $dom->getElementsByTagName('h1') 正在运行。

最佳答案

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

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

disable_html_ns (boolean): Prevents the parser from automatically assigning the HTML5 namespace to the DOM document. This is for non-namespace aware DOM tools.

关于php - 在 PHP 中使用 html5lib 的 Xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25484217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com