Some time we come accross a situation where we have to parse the xml data to array. To achieve that we have used the “SimpleXML” Library available in php. This extension is enabled by default in php.

Sample xml :

[codesyntax lang=”php”]

$xml_data = "<root>
<products>
<product>
<sku>001</sku>
<name>Product 1</name>
<price>100</price>
<weight>10</weight>
<description>Product 1 description</description>
</product>
<product>
<sku>002</sku>
<name>Product 2</name>
<price>100</price>
<weight>10</weight>
<description>Product 2 description</description>
</product>
</products>

</root>"

[/codesyntax]

XML Parsing :

[codesyntax lang=”php”]

$xml = new SimpleXMLElement($xml_data);

[/codesyntax]

Convert XML to Array

We have defined a function “xml2array” which will recursively get called and return an array as final output .

[codesyntax lang=”php”]

function xml2array(){
   $arr = array();
    foreach ($xml as $element)
    {
            $tag = $element->getName();
            $e = get_object_vars($element);
            if (!empty($e))
            {
                     $arr[$tag][] = $element instanceof SimpleXMLElement ? xml2array($element) : $e;
             }
            else
           {
                 $arr[$tag] = trim($element);
            }
    }
    return $arr;
}

$xml_data_in_array = xml2array($xml) -- $xml is the xml object.

[/codesyntax]