Getting an element from the PHP DOM and changing its value

I use PHP / Zend to load html into the DOM and then get the specific div id that I want to change.

$dom = new Zend_Dom_Query($html);
$element = $dom->query('div[id="someid"]');

How to change the text / content / html displayed inside this $elementdiv and then save the changes to $domor $htmlso that I can print the changed html. Any idea how to do this?

+1
source share
1 answer

Zend_Dom_Query is only for the dom query, so it does not provide an interface in itself to change the dom and save it, but it does provide PHP Native DOM objects that will allow you to do this. Something like this should work:

$dom = new Zend_Dom_Query($html);
$document = $dom->getDocument();
$elements = $dom->query('div[id="someid"]');

foreach($elements AS $element) {
    //$element is an instance of DOMElement (http://www.php.net/DOMElement)

    //You have to create new nodes off the document
    $node = $document->createElement("div", "contents of div");
    $element->appendChild($node)
}

$newHtml = $document->saveXml();

PHP Doc DOMElement, , dom:

http://www.php.net/DOMElement

+3

All Articles