Is there any way to convert json to xml in PHP?
Is there any way to convert json
to xml
in PHP
? I know that xml to json is ve开发者_JAVA百科ry much possible.
If you're willing to use the XML Serializer from PEAR, you can convert the JSON to a PHP object and then the PHP object to XML in two easy steps:
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;
}
}
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).
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)
Crack open the JSON with json_decode
, and traverse it to generate whatever XML you want.
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.
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;
}
}
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");
}
Another option would be to use a JSON streaming parser.
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 XMLWriter
directly while reading the document with the streaming parser.
One example would be 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:
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.
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.
精彩评论