Getting an element from PHP DOM and changing its value

房东的猫 提交于 2019-12-24 15:36:32

问题


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:


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



来源:https://stackoverflow.com/questions/9936622/getting-an-element-from-php-dom-and-changing-its-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!