复制 XML 属性 PHP
我需要使用 XML 文档,并且需要将一些字段复制到另一个 XML 文件。 我有这个字段:
<cast>
<person name="Nanda Anand" character="" job="Director" id="589088" thumb="" department="Directing" url="http://www.themoviedb.org/person/589088" order="0" cast_id="1000"/>
<person name="Lynn Collins" character="" job="Actor" id="21044" thumb="http://cf2.imgobject.com/t/p/w185/berS11tKvXqTFThUWAYrH279cvn.jpg" department="Actors" url="http://www.themoviedb.org/person/21044" order="0" cast_id="1001"/>
</cast>
我需要将所有元素复制到另一个 XML,但带有属性数据。 我使用这段代码,但它不起作用:
foreach ($movies->movies->movie->cast->children() as $person)
{
$person = $cast->appendChild(
$xmldoc->createElement(("person"), str_replace("&", "&",$person)));
}
I need to work with XML documents and I need to copy some fields to another XML file.
I have this field:
<cast>
<person name="Nanda Anand" character="" job="Director" id="589088" thumb="" department="Directing" url="http://www.themoviedb.org/person/589088" order="0" cast_id="1000"/>
<person name="Lynn Collins" character="" job="Actor" id="21044" thumb="http://cf2.imgobject.com/t/p/w185/berS11tKvXqTFThUWAYrH279cvn.jpg" department="Actors" url="http://www.themoviedb.org/person/21044" order="0" cast_id="1001"/>
</cast>
I need to copy all the elements to the another XML but with the attributes data..
I use this code, but it doesn't work:
foreach ($movies->movies->movie->cast->children() as $person)
{
$person = $cast->appendChild(
$xmldoc->createElement(("person"), str_replace("&", "&",$person)));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想要操作 XML 文档(即将节点从一个文档添加到另一个文档),您应该使用 DOMDocument,而不是 SimpleXML。
下面是一些使用 DOMDocument 从一个文档复制到另一个文档的代码。请注意,这是一个两步过程。首先将节点作为 $ndTemp 导入到文档中。其次,将导入的 $ndTemp 附加到指定的父节点(我只使用根 documentElement,但它可以是另一个节点)。
注意:如果您只是做一个简单的复制,您可能需要考虑使用 XSL,但那是另一篇文章了...
输入 XML (movie.xml)
PHP
输出
If you want to manipulate an XML document (ie adding nodes from one document to another), you should be using DOMDocument, not SimpleXML.
Here's some code to copy from one document to another using DOMDocument. Note, it's a two step process. First import the node into the document as $ndTemp. Second, append the imported $ndTemp to a specified parent (I just use the root documentElement, but it could be another node).
NOTE: if you're just doing a simple copy, you may want to consider using XSL, but that's another post...
Input XML (movie.xml)
PHP
Output
我认为这会起作用,但未经测试
I think this would work, not tested though