将xml文本数组转换为关联数组[重复]

Posted

技术标签:

【中文标题】将xml文本数组转换为关联数组[重复]【英文标题】:convert xml text array to associative array [duplicate] 【发布时间】:2015-10-30 19:26:46 【问题描述】:

我正在使用 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) 但它失败了。有什么办法吗?

【问题讨论】:

谷歌:php SimpleXMLElement ***.com/questions/6578832/… 【参考方案1】:

您的问题是,就目前而言,您的数组只是一个行数组而不是正确的 XML 数组,因此您在解析它时遇到了问题。

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

$myArray = implode($myArray);
$xml = new SimpleXMLElement($myArray);
$myArray = json_decode(json_encode($xml), true));

祝你好运!

【讨论】:

以上是关于将xml文本数组转换为关联数组[重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何在PHP中按字符将数组拆分为关联数组[重复]

当字符串包含 PHP 中的重复键时,如何将字符串转换为关联数组? [复制]

将 PHP 关联数组传入和传出 XML

在Jquery中将表单转换为关联数组[重复]

将关联数组转换为普通数组

php Laravel Collection将数组转换为关联数组