gpt4 book ai didi

php - 将数组转换为 XML 或 JSON

转载 作者:可可西里 更新时间:2023-11-01 00:06:31 25 4
gpt4 key购买 nike

我要转换下面的数组

Array
(
[city] => Array
(
[0] => Array
(
[0] => Rd
[1] => E
)

[1] => B
[2] => P
[3] => R
[4] => S
[5] => G
[6] => C
)

[dis] => 1.4
)

转换为 XML 格式或 JSON。有人可以帮忙吗?

最佳答案

这适用于关联数组。

    function array2xml($array, $node_name="root") {
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$root = $dom->createElement($node_name);
$dom->appendChild($root);

$array2xml = function ($node, $array) use ($dom, &$array2xml) {
foreach($array as $key => $value){
if ( is_array($value) ) {
$n = $dom->createElement($key);
$node->appendChild($n);
$array2xml($n, $value);
}else{
$attr = $dom->createAttribute($key);
$attr->value = $value;
$node->appendChild($attr);
}
}
};

$array2xml($root, $array);

return $dom->saveXML();
}

关于php - 将数组转换为 XML 或 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9152176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com