Convert JSON to XML with PHP


How to convert a JSON text string to an XML document with PHP language?



Currently, there is no built-in function or any standard extension that you can use to convert a JSON text string to an XML document.

But you can use the following PHP example, json_to_xml_converter.php, to convert a JSON text string to an XML document:

# json_to_xml_converter.php
# Copyright (c) 

   $file = fopen($argv[1], "r") or die("Unable to open json file!");
   $json = fread($file,filesize($argv[1]));

   $val = json_decode($json);

   if (json_last_error() == JSON_ERROR_NONE) {
      $dom = new DOMDocument('1.0');
      $dom->formatOutput = true;
    $dom->appendChild(buildXML($dom, "root",$val)); 
   } else {
      print("\njson_decode() error: ".json_last_error_msg()."\n");

function buildXML($dom, $tag, $val) {
   $xml = null; 
   if (is_scalar($val)) { 
    $xml = $dom->createElement($tag, $val);
   } else if (is_array($val)) { 
      $xml = $dom->createElement($tag);
    foreach ($val as $element) {
   } else if (is_object($val)) {
      $xml = $dom->createElement($tag);
    foreach ((array)$val as $key=>$property) {
         $key = keyToTagASCII($key);
         try {
            new DOMElement($key);
         } catch(DOMException $e) {
            print("Invalid key name: (".$key.") - ".$e->getMessage()."\n");
   } else {
      $xml = new DOMElement($tag);
   return $xml;

function keyToTagASCII($key) {
   if (preg_match("/^xml/i", $key)) {
    $key = "_".$key;
   if (preg_match("/^[0-9\.-]/", $key)) {
    $key = "_".$key;
   $key = preg_replace("/[^0-9a-zA-Z\.\-_]/", "_", $key);
   return $key;

Note that this PHP example is limited to JSON objects with property names in ASCII characters only. This simplifies the coding effort to convert JSON property names to XML tag names.

More PHP coding is needed to support other non-ASCII characters that are allowed in XML tag names.

To try the above PHP example, you can enter the following JSON file, json_object.json:

    "a": null,
    "x+y": "X plus Y",
    "x-y": "X minus Y",
    "007": "Double O Seven",
    "fyi.pi": 0.314159e01,
    "fyi:pi": 0.314159e01,
    "fyi_pi": "0.314159e01",
    "fyi>pi": "31.4159e-1",
    "error msg": "Something wrong!"

Then run the above PHP example through the PHP engine with the JSON file provided in the command line:

>\fyicenter\php\php.exe json_to_xml_converter.php json_object.json
<?xml version="1.0"?>
  <x_y>X plus Y</x_y>
  <x-y>X minus Y</x-y>
  <_007>Double O Seven</_007>
  <error_msg>Something wrong!</error_msg>


JSON to XML Converter at

Mapping JSON Values to XML Elements

JSON to XML Conversion

⇑⇑ JSON Tutorials

2023-07-11, 9386🔥, 0💬