数组到 XML,无需 PHP 中的任何库

问题描述 投票:0回答:1

我正在尝试将 XML 转换为 ARRAY,并将 ARRAY 转换为 XML。网上有很多脚本,但几乎每个脚本都使用 SimpleXML 或其他库之类的库。

我可以让几乎所有事情都可以正常工作:https://github.com/nullivex/lib-array2xml

目前,这就是我所拥有的:

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>

这大大变成了数组:

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
                )

        )

)

但是当我尝试转换回 XML 时,我得到了这个......

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

有什么想法吗?几天后无法让它工作......

编辑:我也测试了这个:https://github.com/spatie/array-to-xml

php arrays xml
1个回答
0
投票

我找到了。

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;
            }
© www.soinside.com 2019 - 2024. All rights reserved.