Created
October 30, 2015 10:26
-
-
Save random-robbie/eebe48f3d2b615385e9e to your computer and use it in GitHub Desktop.
JSON TO XML via POST request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$json_post = $_REQUEST['json']; | |
function json_validate($string) | |
{ | |
// decode the JSON data | |
$result = json_decode($string); | |
// switch and check possible JSON errors | |
switch (json_last_error()) { | |
case JSON_ERROR_NONE: | |
$error = ''; // JSON is valid // No error has occurred | |
break; | |
case JSON_ERROR_DEPTH: | |
$error = 'The maximum stack depth has been exceeded.'; | |
break; | |
case JSON_ERROR_STATE_MISMATCH: | |
$error = 'Invalid or malformed JSON.'; | |
break; | |
case JSON_ERROR_CTRL_CHAR: | |
$error = 'Control character error, possibly incorrectly encoded.'; | |
break; | |
case JSON_ERROR_SYNTAX: | |
$error = 'Syntax error, malformed JSON.'; | |
break; | |
// PHP >= 5.3.3 | |
case JSON_ERROR_UTF8: | |
$error = 'Malformed UTF-8 characters, possibly incorrectly encoded.'; | |
break; | |
// PHP >= 5.5.0 | |
case JSON_ERROR_RECURSION: | |
$error = 'One or more recursive references in the value to be encoded.'; | |
break; | |
// PHP >= 5.5.0 | |
case JSON_ERROR_INF_OR_NAN: | |
$error = 'One or more NAN or INF values in the value to be encoded.'; | |
break; | |
case JSON_ERROR_UNSUPPORTED_TYPE: | |
$error = 'A value of a type that cannot be encoded was given.'; | |
break; | |
default: | |
$error = 'Unknown JSON error occured.'; | |
break; | |
} | |
if ($error !== '') { | |
// throw the Exception or exit // or whatever :) | |
$arr = array("error" => "true","reason" => $error ); | |
$errormsg = json_encode($arr); | |
return $errormsg; | |
} | |
// everything is OK | |
return $result; | |
} | |
/** | |
* 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; | |
} | |
} | |
$result = json_validate($json_post); | |
echo json_to_xml($result); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
requires pear package installed XML_Serializer