php 有没有办法在PHP中将json转换为xml?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/856833/
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-25 00:07:12  来源:igfitidea点击:

Is there any way to convert json to xml in PHP?

phpxmljson

提问by

Is there any way to convert jsonto xmlin PHP? I know that xml to json is very much possible.

有什么办法可以转换jsonxmlinPHP吗?我知道 xml 到 json 很有可能。

回答by Samir Talwar

If you're willing to use the XML Serializerfrom PEAR, you can convert the JSON to a PHP object and then the PHP object to XML in two easy steps:

如果您愿意使用PEAR的XML Serializer,您可以通过两个简单的步骤将 JSON 转换为 PHP 对象,然后将 PHP 对象转换为 XML:

include("XML/Serializer.php");

function json_to_xml($json) {
    $serializer = new XML_Serializer();
    $obj = json_decode($json);

    if ($serializer->serialize($obj)) {
        return $serializer->getSerializedData();
    }
    else {
        return null;
    }
}

回答by Tomalak

It depends on how exactly you want you XML to look like. I would try a combination of json_decode()and the PEAR::XML_Serializer(more info and examples on sitepoint.com).

这取决于您希望 XML 看起来像什么。我会尝试结合json_decode()PEAR::XML_Serializer更多信息和示例在 sitepoint.com 上)。

require_once 'XML/Serializer.php';

$data = json_decode($json, true)

// An array of serializer options
$serializer_options = array (
  'addDecl' => TRUE,
  'encoding' => 'ISO-8859-1',
  'indent' => '  ',
  'rootName' => 'json',
  'mode' => 'simplexml'
); 

$Serializer = &new XML_Serializer($serializer_options);
$status = $Serializer->serialize($data);

if (PEAR::isError($status)) die($status->getMessage());

echo '<pre>';
echo htmlspecialchars($Serializer->getSerializedData());
echo '</pre>';

(Untested code - but you get the idea)

(未经测试的代码 - 但你明白了)

回答by Marcelo Cantos

Crack open the JSON with json_decode, and traverse it to generate whatever XML you want.

用 破解打开 JSON json_decode,并遍历它以生成您想要的任何 XML。

In case you're wondering, there is no canonical mapping between JSON and XML, so you have to write the XML-generation code yourself, based on the needs of your application.

如果您想知道,JSON 和 XML 之间没有规范映射,因此您必须根据应用程序的需要自己编写 XML 生成代码。

回答by spiky

I combined the two earlier suggestions into:

我将之前的两个建议合并为:

/**
 * Convert JSON to XML
 * @param string    - json
 * @return string   - XML
 */
function json_to_xml($json)
{
    include_once("XML/Serializer.php");

    $options = array (
      'addDecl' => TRUE,
      'encoding' => 'UTF-8',
      'indent' => '  ',
      'rootName' => 'json',
      'mode' => 'simplexml'
    );

    $serializer = new XML_Serializer($options);
    $obj = json_decode($json);
    if ($serializer->serialize($obj)) {
        return $serializer->getSerializedData();
    } else {
        return null;
    }
}

回答by 131

A native approch might be

本机方法可能是

function json_to_xml($obj){
  $str = "";
  if(is_null($obj))
    return "<null/>";
  elseif(is_array($obj)) {
      //a list is a hash with 'simple' incremental keys
    $is_list = array_keys($obj) == array_keys(array_values($obj));
    if(!$is_list) {
      $str.= "<hash>";
      foreach($obj as $k=>$v)
        $str.="<item key=\"$k\">".json_to_xml($v)."</item>".CRLF;
      $str .= "</hash>";
    } else {
      $str.= "<list>";
      foreach($obj as $v)
        $str.="<item>".json_to_xml($v)."</item>".CRLF;
      $str .= "</list>";
    }
    return $str;
  } elseif(is_string($obj)) {
    return htmlspecialchars($obj) != $obj ? "<![CDATA[$obj]]>" : $obj;
  } elseif(is_scalar($obj))
    return $obj;
  else
    throw new Exception("Unsupported type $obj");
}

回答by Gordon

Another option would be to use a JSON streaming parser.

另一种选择是使用JSON 流解析器

Using a streamer parser would come in handy if you want to bypass the intermediate object graph created by PHP when using json_decode. For instance, when you got a large JSON document and memory is an issue, you could output the XML with XMLWriterdirectly while reading the document with the streaming parser.

如果您想在使用json_decode. 例如,当您获得一个大型 JSON 文档并且内存有问题时,您可以XMLWriter在使用流式解析器读取文档时直接输出 XML 。

One example would be https://github.com/salsify/jsonstreamingparser

一个例子是https://github.com/salsify/jsonstreamingparser

$writer = new XMLWriter;
$xml->openURI('file.xml');
$listener = new JSON2XML($writer); // you need to write the JSON2XML listener
$stream = fopen('doc.json', 'r');
try {
    $parser = new JsonStreamingParser_Parser($stream, $listener);
    $parser->parse();
} catch (Exception $e) {
    fclose($stream);
    throw $e;
}

The JSON2XML Listener would need to implement the Listener interface:

JSON2XML Listener 需要实现Listener 接口

interface JsonStreamingParser_Listener 
{
  public function start_document();
  public function end_document();
  public function start_object();
  public function end_object();
  public function start_array();
  public function end_array();
  public function key($key);
  public function value($value);
}

At runtime, the listener will receive the various events from the parser, e.g. when the parser finds an object, it will send the data to the start_object()method. When it finds an array, it will trigger start_array()and so on. In those methods you'd then delegate the values to the appropriate methods in the XMLWriter, e.g. start_element()and so on.

在运行时,侦听器将接收来自解析器的各种事件,例如,当解析器找到一个对象时,它会将数据发送给start_object()方法。当它找到一个数组时,它会触发start_array()等等。在这些方法中,您可以将值委托给XMLWriter, eg 中的适当方法start_element(),依此类推。

Disclaimer:I am not affiliated with the author, nor have I used the tool before. I picked this library because the API looked sufficiently simple to illustrate how to use an event based JSON parser.

免责声明:我与作者无关,之前也没有使用过该工具。我选择这个库是因为 API 看起来足够简单,可以说明如何使用基于事件的 JSON 解析器。