egurb
egurb

Reputation: 1216

Getting and echo element including content by ID using PHP

I am trying to get an element from external page (div tag including some content) by its ID and print it to another page on a site. I am trying to use the code below however getting tag errors which I have in the including element (figcaption, figure). Is there anyway to include only a single div by its ID from another page?

PHP

$doc = new DOMDocument();
$doc->loadHTMLFile($_SERVER['DOCUMENT_ROOT'].'/assets/includes/example.html');

$example = $doc->getElementById('test');

echo $example->nodeValue;

?>

HTML

<div id="test">
    <figure>
        <img src="img1.jpg" alt="img" />
        <figcaption></figcaption>
    </figure>
</div>

Upvotes: 1

Views: 137

Answers (2)

fusion3k
fusion3k

Reputation: 11689

DOMDocument output errors on HTML5 even if there are not error, due to impossibility of DTD check.

To avoid this, simply change your code in this way:

libxml_use_internal_errors( True );
$doc->loadHTMLFile( '$_SERVER['DOCUMENT_ROOT'].'/assets/includes/example.html' );

Anyway — even if some errors are displayed — your code load correctly HTML document, but you can't display the <div> because you use a wrong syntax: change echo $example->nodeValue with:

echo $doc->saveHTML( $example );

The right syntax to print DOM HTML is DOMDocument->saveHTML(), or — if you want print only part of document — DOMDocument->saveHTML( DOMElement ).

Also note that DOMDocument is designed to not try to preserve formatting from the original document, so you probably don't obtain this:

<div id="test">
    <figure>
        <img src="img1.jpg" alt="img" />
        <figcaption></figcaption>
    </figure>
</div>

but this:

<div id="test">
    <figure><img src="img1.jpg" alt="img"><figcaption></figcaption></figure>
</div>

Upvotes: 1

Rene Korss
Rene Korss

Reputation: 5484

You are currenlt only echo-ing node value, which will be text. Since you have no text in #test, nothing will output.

You have to print it as HTML:

echo $doc->saveHTML($example);

Upvotes: 1

Related Questions