phpdomdocumentphp-8.4

how to use DomDocument's querySelector in PHP 8.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


Solution

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

    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