dale Nale
dale Nale

Reputation: 21

getting the source code of remote page then display only one div based on its id

exactly as its descriped in the title currently my code is:

<?php
    $url = "remotesite.com/page1.html";
    $html = file_get_contents($url);
    $doc = new DOMDocument(); // create DOMDocument
    libxml_use_internal_errors(true);
    $doc->loadHTML($html); // load HTML you can add $html

    $elements = $doc->getElementsByTagName('div');

?>

my coding skills are very basic so at this point i am lost and dont know how to display only the div that has the id id=mydiv

Upvotes: 0

Views: 1191

Answers (1)

Levi
Levi

Reputation: 12472

If you have PHP 5.3.6 or higher you can do the following:

$url = "remotesite.com/page1.html";
$html = file_get_contents($url);
$doc = new DOMDocument(); // create DOMDocument
libxml_use_internal_errors(true);
$doc->loadHTML($html); // load HTML you can add $html
$testElement = $doc->getElementById('divIDName');
echo $doc->saveHTML($testElement);

http://php.net/manual/en/domdocument.getelementbyid.php

If you have a lower version I believe you would need to copy the Dom node once you found it with getElementById into a new DomDocument object.

$elementDoc = new DOMDocument();
$cloned = $testElement->cloneNode(TRUE);
$elementDoc->appendChild($elementDoc->importNode($cloned,TRUE));
echo $elementDoc->saveHTML();

Upvotes: 1

Related Questions