将xml文本数组转换为关联数组

时间:2015-08-07 11:06:23

标签: php arrays xml

我正在使用API​​,并在提交API后回复我的xml文本数组:

$myArray =  array(
    "<?xml version='1.0' encoding='UTF-8'?>",
    "<invoices>",
    "  <invoice>",
    "    <name>Odin</name>",
    "    <zip>0000</zip>",
    "    <city>Asgard</city>",
    "    <lines>",
    "      <line>",
    "        <itemNo>1</itemNo>",
    "        <qty>1.00</qty>",
    "        <prodCode>usb01T</prodCode>",
    "        <desc>USB 1TB</desc>",
    "        <unitPrice>1000.00</unitPrice>",
    "        <tax>25</tax>",
    "        <lineTaxAmount>250.00</lineTaxAmount>",
    "        <lineTotal>1250.00</lineTotal>",
    "      </line>",
    "    </lines>",
    "    <optional>",
    "      <invoiceType>ordinary</invoiceType>",
    "      <invoiceNo>9</invoiceNo>",
    "      <orderNo>119</orderNo>",
    "      <invoiceDate>07.08.15</invoiceDate>",
    "      <dueDate>21.08.15</dueDate>",
    "      <orderDate>07.08.15</orderDate>",
    "      <state>sent</state>",
    "      <recipientNo>119</recipientNo>",
    "      <address1>Valhalla</address1>",
    "      <country>NORGE</country>",
    "      <email>test@vallhalla.com</email>",
    "      <phone>000000</phone>",
    "      <yourRef>Asgard</yourRef>",
    "      <tax>250.00</tax>",
    "      <total>1250.00</total>",
    "      <accountNo>97101013352</accountNo>",
    "      <orgNo>0000000</orgNo>",
    "      <dunningFee>65.00</dunningFee>",
    "      <interestRate>9.00</interestRate>",
    "    </optional>",
    "  </invoice>","</invoices>"
);

我想将该数组转换为关联数组,因此它看起来像:

$myArray = array(
            'invoices' => array(
                   'invoice' => array(
                       'name' => 'Odin',
                       'zip' => '0000',
            .....
)

我尝试了json_decode(json_encode($ myArray),true)但它失败了。反正有吗?

1 个答案:

答案 0 :(得分:1)

您的问题是,就目前而言,您的数组只是一个行数组而不是正确的XML数组,因此您需要解析它。

要解决此问题,只需连接$myArray并将其解析为XML,然后再通过JSON编码运行:

$myArray = implode($myArray);
$xml = new SimpleXMLElement($myArray);
$myArray = json_decode(json_encode($xml), true));
祝你好运!

相关问题