根据https://www.php.net/manual/en/dom-parentnode.queryselector.php Dom\ParentNode::querySelector 在 PHP >= 8.4.0 中受支持。据此,我认为以下代码可以工作:
$html = '<p><a href="blahblah">blahblah</a></p>';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
libxml_clear_errors();
$test = $doc->querySelector('a');
echo $test->getAttribute('href');
但是,当我在 PHP 8.4.3 上运行它时,出现此错误:
Fatal error: Uncaught Error: Call to undefined method DOMDocument::querySelector()
它在 3v4l.org 上:
请注意,对于 PHP 8.4,您需要使用不同的文档对象:
DOM\HTMLDocument
/DOMDocument
现在,您可以通过这种方式升级代码,如果您使用旧类名的别名,则只需进行加载:
它在 3v4l.org 上:https://3v4l.org/JAhV6#v8.4.3