Simplexml插入子元素

时间:2013-06-25 15:58:34

标签: simplexml

我有一个xml文件相同:

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <prod id="1">
       <layer id="layer_0" imgSRC="data/361_layer_0.png"/>
       <layer id="layer_1" imgSRC="data/362_layer_0.png"/>
       <layer id="layer_2" imgSRC="data/363_layer_0.png"/>
     </prod>
     <prod id="2">
       <layer id="layer_0" imgSRC="data/361_layer_0.png"/>
       <layer id="layer_1" imgSRC="data/362_layer_0.png"/>
       <layer id="layer_2" imgSRC="data/363_layer_0.png"/>
     </prod>
</data>

如何使用simplexml将项目插入图层id =“layer_3”,如下图所示:

 <prod id="1">
   <layer id="layer_0" imgSRC="data/361_layer_0.png"/>
   <layer id="layer_1" imgSRC="data/362_layer_0.png"/>
   <layer id="layer_2" imgSRC="data/363_layer_0.png"/>
       <layer id="layer_3" imgSRC="data/364_layer_0.png"/>
 </prod>

我该怎么办? 谢谢!

1 个答案:

答案 0 :(得分:0)

(1)选择将成为新孩子父母的节点,我选择xpath

$xml = simplexml_load_string($x); // assuming XML in $x
$node = $xml->xpath("//prod[@id='2']/layer[@id='layer_2']")[0];

xpath将选择<layer>id=layer_2<prod>id=2[0]PHP >= 5.4节点作为父级。如果有多个结果,example #10将只选择第一个结果。这适用于simplexml

看到这个有效:http://3v4l.org/5Q46F

(2)然后添加子项及其属性,请参阅{{1}}手册中的{{1}}:

http://www.php.net/manual/en/simplexml.examples-basic.php