从 PHP DOM 获取元素并更改其值 [英] Getting an element from PHP DOM and changing its value

查看:28
本文介绍了从 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

这篇关于从 PHP DOM 获取元素并更改其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆