Asked 7 years ago
29 Dec 2016
Views 1049

posted

how to convert xml to array in php ?

working with cruise api , i am getting lots of xml response and very good at array than the xml so i want to convert xml response to array in php . is that any good library or something will help to convert xml to array in php

<InvoicePricingResponse>
      <Voyage Number="R121" FareCode="FIT" SailDate="2011-05-28" Duration="17" ShipCode="RU" Category="OS" />
      <Currency>
GBP
      </Currency>
      <PriceTimeStamp>
2010-08-13T06:51:16
      </PriceTimeStamp>
      <Totals>
        <Deposit Amount="816.00" DueDate="2010-08-13" />
        <Balance Amount="8158.00" DueDate="2011-04-02" />
        <Cancellation Amount="" />
      </Totals>
</InvoicePricingResponse>

fatso

fatso
answered Apr 24 '23 00:00

In PHP, you can convert an XML string to an array using the simplexml_load_string () function to load the XML data and then convert the resulting object to an array using the json_encode () and json_decode () functions. This approach provides a quick and easy way to parse XML data in PHP without requiring additional libraries.

Here's an example of how to convert an XML string to an array in PHP:


l

$xmString = '<root><node1>value1</node1><node2>value2</node2></root>';

$xmlObject = simplexml_load_string($xmlString);
$jsonString = json_encode($xmlObject);
$array = json_decode($jsonString, true);


print_r($array);
In this example, we start with an XML string stored in the xmlString $ variable. We then use the simplexml_load_string () function to load the XML data into an object. Next, we use the json_encode () function to convert the object to a JSON string, and then we use the json_decode () function with the true flag to convert the JSON string to an associative array.

The resulting array contains the same data as the original XML string. You can access the values of the nodes using their keys in the array. For example, $array ['node1'] would return the value 'value1' . This method is useful when you need to parse XML data and use it in your PHP code.
Post Answer