PHP: Appending (adding) html content to exsisting element by ID

Ryan Kauk picture Ryan Kauk · Aug 25, 2015 · Viewed 21.1k times · Source

I need to search for an element by ID using PHP then appending html content to it. It seems simple enough but I'm new to php and can't find the right function to use to do this.

$html = file_get_contents('http://example.com');
$doc = new DOMDocument(); 
libxml_use_internal_errors(true);
$doc->loadHTML($html);
$descBox = $doc->getElementById('element1');

I just don't know how to do the next step. Any help would be appreciated.

Answer

Alan  picture Alan · Jan 5, 2017

you can also append this way

$html = '
<html>
    <body>
        <ul id="one">
            <li>hello</li>
            <li>hello2</li>
            <li>hello3</li>
            <li>hello4</li>
        </ul>
    </body>
</html>';
libxml_use_internal_errors(true);
$doc = new DOMDocument(); 
$doc->loadHTML($html);
//get the element you want to append to
$descBox = $doc->getElementById('one');
//create the element to append to #element1
$appended = $doc->createElement('li', 'This is a test element.');
//actually append the element
$descBox->appendChild($appended);
echo $doc->saveHTML();

dont forget to saveHTML on the last line