PHP - 使用简单 XML 复制 XML 节点 [英] PHP - Duplicate XML node using Simple XML

查看:28
本文介绍了PHP - 使用简单 XML 复制 XML 节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Simple XML 加载 XML 源,复制现有节点及其所有子节点,然后在呈现 XML 之前自定义此新节点的属性.有什么建议吗?

I need to load an XML source using Simple XML, duplicate an existing node with all his children, then customize an attribute of this new node before rendering XML. Any suggestion?

推荐答案

SimpleXML 不能做到这一点,所以你必须使用 DOM.好消息是 DOM 和 SimpleXML 是同一个硬币 libxml 的两个方面.因此,无论您使用 SimpleXML 还是 DOM,您都在处理同一棵树.举个例子:

SimpleXML can't do this, so you'll have to use DOM. The good news is that DOM and SimpleXML are two sides of the same coin, libxml. So no matter whether you're using SimpleXML or DOM, you're working on the same tree. Here's an example:

$thing = simplexml_load_string(
    '<thing>
        <node n="1"><child/></node>
    </thing>'
);

$dom_thing = dom_import_simplexml($thing);
$dom_node  = dom_import_simplexml($thing->node);
$dom_new   = $dom_thing->appendChild($dom_node->cloneNode(true));

$new_node  = simplexml_import_dom($dom_new);
$new_node['n'] = 2;

echo $thing->asXML();

<小时>

如果你经常做这种事情,你可以试试 SimpleDOM,它是 SimpleXML 的扩展,可让您直接使用 DOM 的方法,而无需在 DOM 对象之间进行转换.


If you're doing that kind of thing a lot, you can try SimpleDOM, which is an extension to SimpleXML that lets you use DOM's methods directly, without converting from and to DOM objects.

include 'SimpleDOM.php';
$thing = simpledom_load_string(
    '<thing>
        <node n="1"><child/></node>
    </thing>'
);

$new = $thing->appendChild($thing->node->cloneNode(true));
$new['n'] = 2;

echo $thing->asXML();

这篇关于PHP - 使用简单 XML 复制 XML 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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