1。我能做什么
我知道如何将 XML 转换为多维 PHP 数组,我这样做:
$xml = file_get_contents('data.xml');
$data = json_decode(json_encode((array) simplexml_load_string($xml)),1);
现在 $data
是我的 PHP 数组。
2。我应该能够做什么
但是如果我更改了该数组并想将其放回到文件中怎么办?我应该能够做相反的事情吧?但我不知道如何...
3。什么不能解决我的问题
这篇文章很接近,但没有以相同的顺序返回数据:How to convert array to SimpleXML
它不应该变得这么困难,对吗?:Convert multidimensional array into XML
最佳答案
我遇到了同样的问题,并且在寻找简单解决方案时遇到了困难。下面的解决方案利用 DOMDocument 来实现 pretty-print 。如果您不想 pretty-print ,请设置 $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
使用以下测试数据并调用:
$array = [
'name' => 'ABC',
'email' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdd8d0dcd4d1fdd8d0dcd4d193ded2d0" rel="noreferrer noopener nofollow">[email protected]</a>',
'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');
您将得到以下结果:
<?xml version="1.0" encoding="UTF-8"?>
<contact>
<name>ABC</name>
<email><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec89818d8580ac89818d8580c28f8381" rel="noreferrer noopener nofollow">[email protected]</a></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>
我希望这会有所帮助。
关于php - 如何将多维 PHP 数组转换为 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330983/