1

I am using an API and after submit something that API responds me an xml text array:

$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>[email protected]</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>"
);

I want to convert that array to associative array so it will look like:

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

I tried json_decode(json_encode($myArray), true) but it fails. Is there anyway to do that?

2

1 Answer 1

1

Your issue is that as it stands, your array is simply an array of lines rather than a correct XML array, hence your issues parsing it.

To solve this issue, simply concatenate $myArray and parse it as XML before running it through your JSON encoding:

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

Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.