Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

php

xml

People also ask

Can we convert JSON to XML?

To convert a JSON document to XML, follow these steps: Select the JSON to XML action from the Tools > JSON Tools menu. Choose or enter the Input URL of the JSON document. Choose the path of the Output file that will contain the resulting XML document.

Can PHP return JSON?

You can simply use the json_encode() function to return JSON response from a PHP script. Also, if you're passing JSON data to a JavaScript program, make sure set the Content-Type header.


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;
    }
}