Search code examples
phphtmlincludeechoinclude-path

including a specific html element from another site using php echo


im brand new to php (started yesterday) ive got a decent background of html/css and a bit of js so i though id give it a shot.

Im trying to build a simple application to teach myself php and i wanted to reference a piece of html from another site, for example the div :

<div id="name"> <p>Sam</p> </div> on the page "http://www.example.com/about.php"

what i was trying was <?php echo file_get_contents("http://www.example.com #name"); ?> is that the right way to go about it ?

i was also couldnt work out if it was better to use include echo or echo file_get_contents

sorry for such a basic question


Solution

  • That can be done with DOMDocument, here's an example:

    $doc = new DOMDocument();
    $doc->loadHTMLFile('http://example.com/');
    
    // get the element that has id=name
    $result = $doc->getElementById('name');
    
    echo $result->nodeValue; // prints: Sam
    
    // or print out $result to see all of the properties
    print_r($result);