Search code examples
phpdomxpathdomdocumentdomxpath

PHP: Xpath query for classname and echo result


I have this very simple HTML page (extract.html) with this content:

<html>
<body>
    <span class="price_value">
     20.50
    </span>

    <table id="data" class="outer">
        <tr><td>Happy</td><td>Sky</td></tr>
        <tr><td>Happy</td><td>Sky</td></tr>
        <tr><td>Happy</td><td>Sky</td></tr>
        <tr><td>Happy</td><td>Sky</td></tr>
        <tr><td>Happy</td><td>Sky</td></tr>
    </table>
</body>

I want to get the value of class price_value (20.50) with this code:

<?php
$doc = new DOMDocument();
$doc->loadHTML("extract.html");
$doc->preserveWhiteSpace = false;


$finder = new DomXPath($doc);
$spaner = $finder->query("(//span[@class='price_value'])[1]");
print_r($spaner);
?>

However the only output i recieve is this:

DOMNodeList Object ( [length] => 0 )

Why is it not finding and printing the contents of the classname i specified?


Solution

  • DOMDocument::loadHTML() function expects HTML string parameter, not an HTML file name. You're expected to use DOMDocument::loadHTMLFile() function instead to load from HTML file :

    $doc = new DOMDocument();
    $doc->loadHTMLFile("extract.html");
    .....