如何将多维 PHP 数组转换为 XML?

Pep*_*les 2 php xml arrays type-conversion

1.我能做什么

我知道如何将 XML 转换为多维 PHP 数组,我这样做:

$xml = file_get_contents('data.xml');
$data = json_decode(json_encode((array) simplexml_load_string($xml)),1);
Run Code Online (Sandbox Code Playgroud)

现在$data是我的 PHP 数组。

2.我应该做什么

但是如果我更改了该数组并想将其放回到文件中怎么办?我应该能够做相反的事情吧?但我不知道如何..

3.什么不能解决我的问题

这篇文章很接近,但没有以相同的顺序返回数据:How to conversion array to SimpleXML

它不应该变得如此困难,对吧?:将多维数组转换为 XML

小智 5

我遇到了同样的问题,并且无法找到简单的解决方案。下面的解决方案利用 DOMDocument 来实现漂亮打印。如果你不想漂亮打印设置 $doc->formatOutput = FALSE;

我谦虚地提交以下 PHP 函数:

function array2xml($data, $name='root', &$doc=null, &$node=null){
    if ($doc==null){
        $doc = new DOMDocument('1.0','UTF-8');
        $doc->formatOutput = TRUE;
        $node = $doc;
    }

    if (is_array($data)){
        foreach($data as $var=>$val){
            if (is_numeric($var)){
                array2xml($val, $name, $doc, $node);
            }else{
                if (!isset($child)){
                    $child = $doc->createElement($name);
                    $node->appendChild($child);
                }

                array2xml($val, $var, $doc, $child);
            }
        }
    }else{
        $child = $doc->createElement($name);
        $node->appendChild($child);
        $textNode = $doc->createTextNode($data);
        $child->appendChild($textNode);
    }

    if ($doc==$node) return $doc->saveXML();
}//array2xml
Run Code Online (Sandbox Code Playgroud)

使用以下测试数据并调用:

$array = [
    'name'   => 'ABC',
    'email'  => 'email@email.com',
    'phones' =>
    [
        'phone' =>
        [
            [
                'mobile' => '9000199193',
                'land'   => '9999999',
            ],
            [
                'mobile' => '9000199193',
                'land'   => '9999999',
            ],
            [
                'mobile' => '9000199194',
                'land'   => '5555555',
            ],
            [
                'mobile' => '9000199195',
                'land'   => '8888888',
            ],
        ],
    ],
];

//Specify the $array and a name for the root container
echo array2xml($array, 'contact');
Run Code Online (Sandbox Code Playgroud)

您将得到以下结果:

<?xml version="1.0" encoding="UTF-8"?>
<contact>
  <name>ABC</name>
  <email>email@email.com</email>
  <phones>
    <phone>
      <mobile>9000199193</mobile>
      <land>9999999</land>
    </phone>
    <phone>
      <mobile>9000199193</mobile>
      <land>9999999</land>
    </phone>
    <phone>
      <mobile>9000199194</mobile>
      <land>5555555</land>
    </phone>
    <phone>
      <mobile>9000199195</mobile>
      <land>8888888</land>
    </phone>
  </phones>
</contact>
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。