【问题标题】:PHP JSON or Array to XMLPHP JSON 或数组到 XML
【发布时间】:2012-03-21 15:18:12
【问题描述】:

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

【问题讨论】:

标签: php xml arrays json


【解决方案1】:

在这里查看:How to convert array to SimpleXML

this 文档也应该对您有所帮助

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

【讨论】:

    【解决方案2】:

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

    $array = json_decode ($someJsonString, true);
    

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

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

    这是我的 arrayToXml() 函数:

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

    【讨论】:

      【解决方案3】:

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

      这里有一个涵盖 array to xml - How to convert array to SimpleXML 的主题,并且可以在 google 上找到许多涵盖 json to xml 的页面,所以我认为这几乎是一个品味问题。

      【讨论】:

        猜你喜欢
        • 2010-12-04
        • 1970-01-01
        • 1970-01-01
        • 2012-08-22
        • 2011-03-26
        • 1970-01-01
        • 1970-01-01
        • 2019-03-28
        • 2019-08-26
        相关资源
        最近更新 更多