使用简单XML添加具有相同名称的子元素

时间:2011-11-10 15:53:38

标签: php xml simplexml

//create a simple xml object
$xml = new SimpleXMLElement('some valid xml');

//add a my_elements node
$xml->addChild('my_elements');

//an array of elements that will be added to to my_elments
$my_elements = array('element_1', 'element_2', 'element_3');

foreach($my_elements as $element){
   //my_element is only added once as shown below
   $xml->my_elements->addChild('my_element');

   $xml->my_elements->my_element->addChild('something', $element);
}

我希望看起来像这样(为了便于阅读,以xml显示)

<xml>
   <my_elements>
      <my_element>
          <something>element_1</something>
      </my_element>
      <my_element>
          <something>element_2</something>
      </my_element>
      <my_element>
          <something>element_3</something>
      </my_element>
   </my_elements>
</xml>

但我得到的更像是这样的

<xml>
   <my_elements>
      <my_element>
         <something>element_1</something>
         <something>element_2</something>
         <something>element_3</something>
      </my_element>
   </my_elements>
</xml>

使用具有相同名称的addChild时是否可以创建单独的子节点?

1 个答案:

答案 0 :(得分:5)

是的,您只需要将子项添加到新添加的元素,而不是现有元素。见http://php.net/manual/en/simplexmlelement.addchild.php

foreach($my_elements as $element){
   //my_element is only added once as shown below
   $new_my_element = $xml->my_elements->addChild('my_element');
   $new_my_element->addChild('something', $element);
}