Monday, 8 September 2014

How to transform XML file into an array ?

The method I have been using to solve that issue is to convert data in these three steps:
1- apply  the function called "simplexml_load_string" to transform an XML content into XML object
2- convert the XML object into JSON format with the "json_encode" function
3- convert the JSON data to an array using  the "json_decode" function


Here the function I have been using when working with webservices  (through URL):

    $tab = json_decode(XmlToJson($xml), true);

    function XmlToJson($fileContents)
    {
        $fileContents = str_replace(array(
            "\n",
            "\r",
            "\t"
        ), '', $fileContents);
        $fileContents = trim(str_replace('"', "'", $fileContents));
        $fileContents = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $fileContents);
        $fileContents = preg_replace('/xmlns[^=]*="[^"]*"/i', '', $fileContents);
        $fileContents = preg_replace('/[a-zA-Z]+:([a-zA-Z]+[=>])/', '$1', $fileContents);
        $simpleXml = @simplexml_load_string($fileContents);
       
        //$tab = (array) $simpleXml;
       
        $json = json_encode($simpleXml);
        return $json;
    }