-1

我有一个 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>

我需要做什么?谢谢!!

4

1 回答 1

0

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

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

xpath将选择所有具有with作为父<layer>节点的节点。如果有多个结果,将只选择第一个。这适用于.id=layer_2<prod>id=2[0]PHP >= 5.4

看到这个工作:http: //3v4l.org/5Q46F

(2)然后添加孩子及其属性,见example #10手册simplexml

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

于 2013-06-25T16:42:10.603 回答