Veer Shrivastav
Veer Shrivastav

Reputation: 5496

php DOM read from webpage

I am new to php DOM, I read about DOMDocument. I am trying to create DOMDocument from a webpage. So, that I can perform DOM operations on the loaded webpage.

I tried this,

<?php
    $dom = new DOMDocument();
    $dom->loadHTMLFile("www.google.com");
    echo($dom->textContent);
?>

I tried several functions like, load,loadHTML...

Later I want to perform operations like, getElementById() etc..

How can I do that.?

Upvotes: 1

Views: 102

Answers (2)

Alf Eaton
Alf Eaton

Reputation: 5463

You need to use an actual URL: $dom->loadHTMLFile("http://www.google.com/");

Upvotes: 0

Nick Bondarenko
Nick Bondarenko

Reputation: 6361

DOMDocument::loadHTMLFile can open just files in local system. So you should download it first.

<php
    $dom = loadHtmlFromWeb("www.google.com");
    echo($dom->textContent);

    /**
     * @param string $url
     *  
     * @return DOMDocument
     */
    function loadHtmlFromWeb($url) {
         $curl = curl_init() ) {
         curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
         $out = curl_exec($curl);
         curl_close($curl);

         $dom = new DOMDocument();
         if (!empty($out)) {
             $dom->loadHTML($out );
         }
         return $dom;
    }   
?>

Upvotes: 2

Related Questions