从 PHP DOM 获取元素并更改其值

问题描述:

我正在使用 PHP/Zend 将 html 加载到 DOM 中,然后我得到一个我想要修改的特定 div id.

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"]');

如何修改 $element div 中显示的 text/content/html,然后将更改保存到 $dom$html 这样我就可以打印修改后的 html.知道如何做到这一点吗?

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?

Zend_Dom_Query 专为查询 dom 量身定制,因此它本身并没有提供接口来更改 dom 并保存它,但它确实公开了PHP Native DOM 对象可以让你这样做.这样的事情应该可以工作:

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();

查看 DOMElement 的 PHP 文档以了解如何更改 dom:

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