is there some way to convert json to xml in PHP? I know that xml to json is very much possible.
+3
A:
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)
Tomalak
2009-05-13 09:01:59
Ack, ya beat me by half a minute. I'll leave mine up anyway - it's a slightly different approach.
Samir Talwar
2009-05-13 09:04:16
+3
A:
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;
}
}
Samir Talwar
2009-05-13 09:03:28
A:
There's the Services_JSON extension from pear.php.net that does exactly what you need. You'll also need the SimpleXMLElement extension. Details and code sample here:
http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/
EDIT: Sorry, I misread the question: my answer is for converting XML to JSON.
scotts
2009-10-24 00:37:44