admin管理员组

文章数量:1201147

According to .queryselector.php Dom\ParentNode::querySelector is supported in PHP >= 8.4.0. Pursuant to that I should think the following code would work:

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

However, when I run it on PHP 8.4.3 I get this error:

Fatal error: Uncaught Error: Call to undefined method DOMDocument::querySelector()

Here it is on 3v4l:

.4.3

According to https://www.php.net/manual/en/dom-parentnode.queryselector.php Dom\ParentNode::querySelector is supported in PHP >= 8.4.0. Pursuant to that I should think the following code would work:

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

However, when I run it on PHP 8.4.3 I get this error:

Fatal error: Uncaught Error: Call to undefined method DOMDocument::querySelector()

Here it is on 3v4l.org:

https://3v4l.org/q9VDR#v8.4.3

Share Improve this question edited Jan 21 at 14:43 hakre 198k55 gold badges446 silver badges854 bronze badges Recognized by PHP Collective asked Jan 21 at 13:50 neubertneubert 16.8k26 gold badges133 silver badges247 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

With PHP 8.4 note you need to use a different document object for that:

  • DOM\HTMLDocument / DOMDocument

You can upgrade your code now this way, it is only about the loading if you alias to the old class name:

use DOM\HTMLDocument as DOMDocument;
#   **NEW** PHP 8.4  as  ^ before ^

$html = '<p><a href="blahblah">blahblah</a></p>';

$doc = DOMDocument::createFromString($html, LIBXML_HTML_NOIMPLIED);
                                            # no <html>...</html> wrap

$test = $doc->querySelector('a');

echo $test->getAttribute('href');

Here it is on 3v4l.org: https://3v4l.org/JAhV6#v8.4.3

本文标签: how to use DomDocument39s querySelector in PHP 843Stack Overflow