Getting an element from PHP DOM and changing its v

2019-08-03 13:19发布

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?

1条回答
老娘就宠你
2楼-- · 2019-08-03 13:44

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

查看更多
登录 后发表回答