有没有一种方法可以将PHP SimpleXMLElement添加到另一个SimpleXMLElement? [英] Is there a way to add a PHP SimpleXMLElement to another SimpleXMLElement?

查看:215
本文介绍了有没有一种方法可以将PHP SimpleXMLElement添加到另一个SimpleXMLElement?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SimpleXMLElement的"addChild"方法似乎应该是正确的选择,但显然只接受代表新子代标记名的字符串.

The "addChild" method of SimpleXMLElement seems like it should be the right choice, but it apparently only takes strings representing the tagname of the new child.

有对象对象表示法,用于引用树的节点并对其进行设置,例如$ simpleXMLNode-> child = value,但这似乎仅适用于简单的文本/数字值.如果我尝试以下操作:

There's the object-ish notation for referencing nodes of the tree and setting them, e.g. $simpleXMLNode->child = value, but that only seems to work for simple text/numeric values. If I try the following:

$s = new SimpleXMLElement('<root/>');
$t = new SimpleXMLElement('<child/>');
$s->a = $t;
echo $s->asXML()

我得到:

<?xml version="1.0"?>
<root><a></a></root>

当我希望的时候:

<?xml version="1.0"?>
<root><a><child/></a></root>

我想到了将$ t转换为字符串,然后添加它(除去XML声明之后):

I thought of converting $t to a string and then adding it (after stripping out the XML declaration):

$s->a = substr($t->asXML(),22)

但这会产生:

<?xml version="1.0"?>
<root><a>&lt;child/&gt;</a></root>

再次,不是我想要的.

是否有使用SimpleXML完成此类操作的典型方法?

Is there a typical way to accomplish this kind of thing with SimpleXML?

推荐答案

嘿,未知.您必须对您的SimpleXML对象使用DOMElement接口才能实现此目的.

Hey unknown. You have to use the DOMElement interface to your SimpleXML objects to achieve this.

<?php

$s = new SimpleXMLElement('<root/>');
$t = new DOMElement('child');

$dom = dom_import_simplexml($s);
$dom->appendChild($t);

echo $s->asXML();
// <root><child/></root>

如果您需要更多具体细节,请告诉我.在文档和dom_import_simplexml()方法的注释中也有几个示例: http://php.net/dom_import_simplexml

If you need more specific details, let me know. There are several examples in the documentation and comments for the dom_import_simplexml() method too: http://php.net/dom_import_simplexml

这篇关于有没有一种方法可以将PHP SimpleXMLElement添加到另一个SimpleXMLElement?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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