Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 736
Ryan Kauk Avatar asked Aug 24 '15 23:08

Ryan Kauk


2 Answers

Like chris mentioned in his comment try using DOMNode::appendChild, which will allow you to add a child element to your selected element and DOMDocument::createElement to actually create the element like so:

$html = file_get_contents('http://example.com');
libxml_use_internal_errors(true);
$doc = new DOMDocument(); 
$doc->loadHTML($html);
//get the element you want to append to
$descBox = $doc->getElementById('element1');
//create the element to append to #element1
$appended = $doc->createElement('div', 'This is a test element.');
//actually append the element
$descBox->appendChild($appended);

Alternatively if you already have an HTML string you want to append you can create a document fragment like so:

$html = file_get_contents('http://example.com');
libxml_use_internal_errors(true);
$doc = new DOMDocument(); 
$doc->loadHTML($html);
//get the element you want to append to
$descBox = $doc->getElementById('element1');
//create the fragment
$fragment = $doc->createDocumentFragment();
//add content to fragment
$fragment->appendXML('<div>This is a test element.</div>');
//actually append the element
$descBox->appendChild($fragment);

Please note that any elements added with JavaScript will be inaccessible to PHP.

like image 153
Baconics Avatar answered Nov 14 '22 22:11

Baconics


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

like image 30
Alan Avatar answered Nov 14 '22 22:11

Alan