数组到xml,并将数据附加到正在退出的xml文件中


array to xml and append data to exting xml file

我已经用下面的函数生成了一个xml文件。

  $orderInfo = Array
  (
     [order_number] => MI100000038
     [customer_id] => 645
     [customer_email] => test@yopmail.com
      [protect_code] => xxxx33639
     [total_qty_ordered] => 4.0000
     [created_at] => 2016-03-25 20:01:05
     [billing_address] => Array
     (
        [street] => Array
            (
                [0] => xxx
            )
        [city] => xx
        [region] => xx
        [postcode] => 848151
        [country_id] => x
        [telephone] => 8745165
    )
   [items] => Array
    (
        [1] => Array
            (
                [name] => fgfgf
                [sku] => 796
                [qty_ordered] => 3.0000
                [price] => 81.2000
                [product_type] => simple
            )
    )
   ) ;
  $xml_order_info = new SimpleXMLElement('<?xml version=''1.0''?><order_info></order_info>");
  $this->array_to_xml($orderInfo,$xml_order_info);
  function array_to_xml($array, &$xml_order_info) {
    foreach($array as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml_order_info->addChild("$key");
                $this->array_to_xml($value, $subnode);
            }else{
                $subnode = $xml_order_info->addChild("item$key");
                $this->array_to_xml($value, $subnode);
            }
        }else {
            $xml_order_info->addChild("$key",htmlspecialchars("$value"));
        }
    }
}
    $xml_file = $xml_order_info->asXML('order.xml');

现在,我想再次使用这个过程,并将数据附加到退出的order.xml文件中。我使用以下代码:

  if (file_exists($xml_order_info_file)) {
        echo '<br/>in';
        $xml = simplexml_load_string($xml_order_info_file);

但它对我不起作用。

simplexml_load_string不需要文件名作为参数,而只需要格式良好的XML字符串:

获取格式正确的XML字符串,并将其作为对象返回。

因此,最好使用simplexml_load_file:

if (file_exists($xml_order_info_file)) {
    echo '<br/>in';
    $xml = simplexml_load_file($xml_order_info_file);