PHP JSON 或数组到 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9544840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:04:45  来源:igfitidea点击:

PHP JSON or Array to XML

phpxmlarraysjson

提问by chris

Whats the easiest way to take a JSON or Array object and convert it to XML. Maybe I am looking in all the wrong places but I am not finding a decent answer to get me on track with doing it. Is this something I would have to somehow build myself? Or is there something like json_encode/json_decode that will take an array or json object and ust pop it out as a xml object?

获取 JSON 或 Array 对象并将其转换为 XML 的最简单方法是什么。也许我正在寻找所有错误的地方,但我没有找到一个体面的答案来让我走上正轨。这是我必须以某种方式建立自己的东西吗?或者有没有像 json_encode/json_decode 这样的东西,它会接受一个数组或 json 对象,然后将它作为一个 xml 对象弹出?

采纳答案by linuxeasy

Check it here: How to convert array to SimpleXML

在此处查看:如何将数组转换为 SimpleXML

and thisdocumentation should help you too

这个文件应帮助您太

Regarding Json to Array, you can use json_decodeto do the same!

关于Json to Array,你可以使用json_decode来做同样的事情!

回答by Michael Yurin

Here is my variant of JSON to XML conversion. I get an array from JSON using json_decode() function:

这是我的 JSON 到 XML 转换的变体。我使用 json_decode() 函数从 JSON 获取一个数组:

$array = json_decode ($someJsonString, true);

Then I convert the array to XML with my arrayToXml() function:

然后我使用 arrayToXml() 函数将数组转换为 XML:

$xml = new SimpleXMLElement('<root/>');
$this->arrayToXml($array, $xml);

Here is my arrayToXml() function:

这是我的 arrayToXml() 函数:

/**
 * Convert an array to XML
 * @param array $array
 * @param SimpleXMLElement $xml
 */
function arrayToXml($array, &$xml){
    foreach ($array as $key => $value) {
        if(is_array($value)){
            if(is_int($key)){
                $key = "e";
            }
            $label = $xml->addChild($key);
            $this->arrayToXml($value, $label);
        }
        else {
            $xml->addChild($key, $value);
        }
    }
}

回答by Pankucins

I am not sure about the easiest way. Both are relatively simple enough as I see it.

我不确定最简单的方法。在我看来,两者都相对简单。

Here's a topic covering array to xml- How to convert array to SimpleXMLand many pages covering json to xmlcan be found on google so I assume it's pretty much a matter of taste.

这是一个涵盖的主题array to xml-如何将数组转换为 SimpleXML并且json to xml可以在 google 上找到许多涵盖的页面,所以我认为这几乎是一个品味问题。