Search code examples
phpdomdocumentfile-get-contents

How can I get html from a specific node using DOMDocument()


I am using $doc = new DOMDocument();

I just want to get HTML from a particular id rather than the whole HTML.

I tried

$file=file_get_contents($url);
    $doc = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput       = true;
    $doc->load($file);
    $content = $doc->getElementById("site-content");
    echo $doc->saveHTML($content);

But it's not working.


Solution

  • <?php
        $file=file_get_contents("https://www.wikipedia.org/");
        $doc = new DOMDocument();
        $doc->loadHtml($file);
        $content = $doc->getElementById("searchInput");
        echo $doc->saveHTML($content);