phparraysxml

ARRAY to XML without any libs in PHP


I'm trying to convert XML to ARRAY and ARRAY to XML. There are a lot of scripts online, but almost every one of them use libs like SimpleXML or something else.

I can make almost everything works fine with this one: https://github.com/nullivex/lib-array2xml

For now, this is what I have :

XML

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <nom>Leaflet</nom>
  <fichiers>
     <fichier type="js" script="externe">leaflet.js</fichier>
     <fichier type="js" script="interne" cdata="true"><![CDATA[TEST]]></fichier>
  </fichiers>
  <activation>0</activation>
</configuration>

which is turn greatly into ARRAY :

Array
(
    [configuration] => Array
        (
            [nom] => Array
                (
                    [#text] => Leaflet
                )

            [fichiers] => Array
                (
                    [fichier] => Array
                        (
                            [0] => Array
                                (
                                    [#text] => leaflet.js
                                    [@type] => js
                                    [@script] => externe
                                )

                            [1] => Array
                                (
                                    [#text] => TEST
                                    [@type] => js
                                    [@script] => interne
                                    [@cdata] => true
                                )

                        )

                )

            [activation] => Array
                (
                    [#text] => 0
                )

        )

)

But when I try to convert back into XML, I have this...

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <nom>Leaflet</nom>
  <fichiers>
    <fichier>leaflet.js</fichier>
    <fichier>TEST</fichier>
  </fichiers>
  <activation>0</activation>
</configuration>

Any idea ? Can't make it works since few days...

Edit: I have also tested this one : https://github.com/spatie/array-to-xml


Solution

  • I had found it.

    if(isset($arr['#text'])) 
                {
                    foreach($arr as $key => $value) 
                    {
                        if(@$key[0]=="@") $node->setAttribute(substr($key, 1), $value);
                    }
                    
                    if(isset($arr['@cdata'])) 
                    {
                        $node->setAttribute('cdata', $arr['@cdata']);
                        $node->appendChild($xml->createCDATASection(self::bool2str($arr['#text'])));
                    }
                    else
                    {
                        $node->appendChild($xml->createTextNode(self::bool2str($arr['#text'])));
                    }
                    unset($arr['#text']);
                    return $node;
                }