嵌套simplexml

时间:2017-10-11 20:22:46

标签: php xml simplexml

尝试使用SimpleXmL来修改xml。需要嵌套一些标签

 $xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><orders></orders>');
        $orderlist = $xml->addChild('order');
        $orderlist->addAttribute('shipdate', date('Y-m-d H:i:s'));

        $orderlist = $xml->addChild('delivery');
        $orderlist->addAttribute('weight', '0');

这将输出:

  <?xml version="1.0" encoding="utf-8"?>
    <orders>
        <order shipdate="2017-10-11 13:44:12" />
        <delivery weight="0" />
    <order/>
    </orders>

但是需要标签不要在标签之前关闭。 希望它看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<orders>
  <order shipdate="2016-07-14T14:41:30">
    <delivery weight="0" />
  </order>
</orders>

2 个答案:

答案 0 :(得分:2)

尝试以下方法:

 $xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><orders></orders>');
        $orderlist = $xml->addChild('order');
        $orderlist->addAttribute('shipdate', date('Y-m-d H:i:s'));

        $delivery = $orderlist->addChild('delivery');
        $delivery->addAttribute('weight', '0');

这会在<delivery>标记内添加<order>标记。并提供如下输出:

<?xml version="1.0" encoding="utf-8"?>
<orders>
    <order shipdate="2017-10-11 22:28:13">
        <delivery weight="0"/>
    </order>
</orders>

答案 1 :(得分:0)

如果要将子项添加到$orderlist,请正确编写:

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><orders></orders>');
// add child to root node `orders`
$orderlist = $xml->addChild('order');
$orderlist->addAttribute('shipdate', date('Y-m-d H:i:s'));

// add child to newly created `order` node
$delivery = $orderlist->addChild('delivery');
$delivery->addAttribute('weight', '0');

echo $xml->asXML();