1

I'm using PHP/Zend to load html into a DOM, and then I get a specific div id that I want to modify.

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

How do I modify the text/content/html displayed inside that $element div, and then save the changes to the $dom or $html so I can print the modified html. Any idea how to do this?

sameold
  • 18,400
  • 21
  • 63
  • 87
  • Just a quick precaution you're better off with regular expressions. I used to go hard on processing with DOM libs because I hated regex. JustHost eventually suspended my hosting account because it consumed too much memory and resources so be careful. Use regular expressions. – Silviu-Marian Mar 30 '12 at 03:42
  • 1
    If you're using Eclipse (or anything based on Eclipse such as Zend Studio), use `/* @var $result DOMElement */` in your `foreach()`, so that it you will autocomplete your `DOMElement` object. – Liyali Mar 30 '12 at 03:53

1 Answers1

3

Zend_Dom_Query is tailored just for querying a dom, so it doesn't provide an interface in and of itself to alter the dom and save it, but it does expose the PHP Native DOM objects that will let you do so. 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();

Take a look at the PHP Doc for DOMElement to get an idea of how you can alter the dom:

http://www.php.net/DOMElement

Brad Harris
  • 1,520
  • 9
  • 12