I have a JSON file from a web service and want to use this data with a Drupal module. However, this module expects XML data. So I have the idea of overwriting the module. To do this, I need to convert the JSON file in XML, and ensure the file changes from JSON to PHP array.

Does any method or library exist to do this or convert .json file to .xml directly?

Now I have an array that is like the following one:

  [0] => stdClass Object(
    [sponsor] => stdClass Object(
      [created_at] =>  

I need to convert this array in:

SimpleXMLElement Object(
  [@attributes] => Array(
    [type] => Array(
      [sponsor] => Array(
        [0] => SimpleXMLElement Object(
          [created-at] =>

2 Answers 2


Using the XML Serializer package, you can use the following code to make the conversion, as reported in this answer on Stack Overflow.

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

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

Alternatively, you can use the following code give in this answer for the same question.

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)) {

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

I had a similar issue where I wanted to mock away a SoapClient and verify the web service payloads generated by our system. I tried working with SimpleXMLElement to parse prepared XML snippets (requests and response) but had several issues with that and ended up writing my own stuff in the end.


(It doesn't handle XML node attributes at all but turned out useful although SoapClient can't be mocked by Phockito.)

Not the answer you're looking for? Browse other questions tagged or ask your own question.