我需要处理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)));
}
答案 0 :(得分:3)
如果您想操作XML文档(即将节点从一个文档添加到另一个文档),您应该使用DOMDocument,而不是SimpleXML。
这是使用DOMDocument从一个文档复制到另一个文档的一些代码。请注意,这是一个两步过程。首先将节点作为$ ndTemp导入文档。其次,将导入的$ ndTemp附加到指定的父级(我只使用根文档元素,但它可能是另一个节点)。
注意:如果你只是做一个简单的副本,你可能想考虑使用XSL,但这是另一篇文章......
输入XML(movie.xml)
<xml>
<movie name='first'>
<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>
</movie>
<movie name='Second'>
<cast>
<person name="Zaphod Beeblebrox" character="" job="Director" id="589088" thumb="" department="Directing" url="http://www.themoviedb.org/person/589088" order="0" cast_id="1000"/>
</cast>
</movie>
</xml>
PHP
<?php
$xml = new DOMDocument();
$strFileName = "movie.xml";
$xml->load($strFileName);
$xmlCopy = new DOMDocument();
$xmlCopy->loadXML( "<xml/>" );
$xpath = new domxpath( $xml );
$strXPath = "/xml/movie/cast/person";
$elements = $xpath->query( $strXPath, $xml );
foreach( $elements as $element ) {
$ndTemp = $xmlCopy->importNode( $element, true );
$xmlCopy->documentElement->appendChild( $ndTemp );
}
echo $xmlCopy->saveXML();
?>
输出
<?xml version="1.0"?>
<xml>
<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" />
<person name="Zaphod Beeblebrox" character="" job="Director" id="589088" thumb="" department="Directing" url="http://www.themoviedb.org/person/589088" order="0" cast_id="1000" />
</xml>
答案 1 :(得分:0)
我认为这样可行,但未经过测试
foreach ($movies->movies->movie->cast->children() as $person)
{
$cast->appendChild($person);
}