How to Convert JSON to XML in PHP (Complete Developer Guide)
Data exchange plays a critical role in modern web development. Applications constantly communicate with databases, APIs, and external services to send and receive structured data.
Two of the most widely used data formats for this purpose are JSON (JavaScript Object Notation) and XML (Extensible Markup Language).
JSON has become the preferred format for modern APIs due to its lightweight structure and fast parsing. However, many legacy systems, enterprise services, and SOAP APIs still require XML.
Because of this, developers frequently need to convert JSON data into XML format when integrating modern systems with older technologies.
In this guide, we will cover:
-
What JSON and XML are
-
Why JSON to XML conversion is needed
-
How to convert JSON to XML in PHP
-
Using SimpleXML in PHP
-
Using DOMDocument
-
Writing a custom JSON-to-XML converter function
-
Best practices for handling data conversion
By the end of this tutorial, you will clearly understand how to perform JSON to XML conversion using PHP.
Understanding JSON
JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that is easy for humans to read and machines to parse.
Example JSON data:
{
"user": {
"name": "John",
"email": "[email protected]",
"age": 30
}
}
JSON is widely used in:
-
REST APIs
-
Web applications
-
Mobile applications
-
JavaScript frameworks
Because JSON integrates naturally with JavaScript, it has become the standard format for modern APIs.
Understanding XML
XML stands for Extensible Markup Language. It is used to store and transport structured data using custom tags.
Example XML format:
<user>
<name>John</name>
<email>[email protected]</email>
<age>30</age>
</user>
XML is commonly used in:
-
Enterprise systems
-
SOAP APIs
-
Data storage systems
-
Configuration files
Even though JSON is more popular today, XML remains important in many industries.
Why Convert JSON to XML in PHP
There are several reasons developers convert JSON data into XML.
Legacy API Integration
Many enterprise APIs still require XML requests.
SOAP Web Services
SOAP services use XML as the standard communication format.
Data Migration
Older systems may require XML-based data structures.
Third-Party Integrations
Some payment gateways and enterprise tools require XML input.
For these reasons, PHP developers often implement JSON to XML conversion.
Step 1: Decode JSON Data in PHP
Before converting JSON into XML, you must first decode the JSON string into a PHP array.
Example:
$json = '{"name":"John","email":"[email protected]","age":30}';
$data = json_decode($json, true);
print_r($data);
The json_decode() function converts JSON into a PHP associative array.
Method 1: Convert JSON to XML Using SimpleXML
PHP provides a built-in library called SimpleXML which makes XML generation easy.
Example code:
function arrayToXml($data, &$xml) {
foreach($data as $key => $value) {
if(is_array($value)) {
$subnode = $xml->addChild($key);
arrayToXml($value, $subnode);
} else {
$xml->addChild($key, htmlspecialchars($value));
}
}
}
$json = '{"name":"John","email":"[email protected]","age":30}';
$array = json_decode($json, true);
$xml = new SimpleXMLElement('<root/>');
arrayToXml($array, $xml);
echo $xml->asXML();
Output XML:
<root>
<name>John</name>
<email>[email protected]</email>
<age>30</age>
</root>
SimpleXML is one of the easiest ways to generate XML in PHP.
Method 2: Convert JSON to XML Using DOMDocument
Another powerful way to create XML in PHP is using the DOMDocument class.
Example:
$json = '{"name":"John","email":"[email protected]","age":30}';
$data = json_decode($json, true);
$xml = new DOMDocument('1.0','UTF-8');
$root = $xml->createElement("root");
$xml->appendChild($root);
foreach($data as $key => $value) {
$node = $xml->createElement($key, $value);
$root->appendChild($node);
}
echo $xml->saveXML();
DOMDocument is useful when you need more control over XML structure.
Handling Nested JSON Objects
JSON often contains nested objects.
Example JSON:
{
"user": {
"name": "John",
"email": "[email protected]"
}
}
Converted XML:
<root>
<user>
<name>John</name>
<email>[email protected]</email>
</user>
</root>
Recursive functions are commonly used to handle nested data structures.
Handling JSON Arrays
Example JSON array:
{
"products": [
{"name":"Laptop"},
{"name":"Mobile"}
]
}
Converted XML:
<products>
<product>
<name>Laptop</name>
</product>
<product>
<name>Mobile</name>
</product>
</products>
Arrays must be handled carefully when converting to XML.
Common Issues During JSON to XML Conversion
Developers may encounter several challenges while converting JSON data.
Invalid JSON Format
If the JSON structure is invalid, the conversion process will fail.
Numeric Keys
JSON arrays sometimes create numeric XML tags which are not valid.
Special Characters
Characters such as < or & must be escaped properly in XML.
Best Practices for JSON to XML Conversion
To ensure reliable conversion, follow these best practices.
Validate JSON First
Always validate JSON before processing.
Use Recursive Functions
Recursive functions help convert nested objects correctly.
Escape Special Characters
Use htmlspecialchars() to avoid XML parsing errors.
Maintain Consistent XML Structure
Ensure generated XML follows a predictable schema.
Real-World Use Cases
JSON to XML conversion is used in many real applications.
API Integrations
Modern systems sending data to legacy APIs.
Payment Gateways
Some gateways require XML requests.
Enterprise Systems
Large organizations often rely on XML data structures.
Data Transformation
Converting data formats during system migrations.
Using an Online JSON to XML Converter
If you do not want to write code manually, you can use an online converter tool.
Online tools allow developers to:
-
Convert JSON instantly
-
Validate data structure
-
Beautify output XML
-
Fix formatting issues
These tools are especially helpful when debugging API responses.
Conclusion
JSON and XML are two powerful formats used for data exchange across applications and APIs.
While JSON is widely used in modern web development, XML still plays an important role in enterprise systems and legacy services.
PHP provides multiple ways to convert JSON into XML, including SimpleXML, DOMDocument, and custom recursive functions.
Choosing the right approach depends on your project requirements and the complexity of the data structure.
Understanding JSON-to-XML conversion will help developers integrate modern applications with older systems more efficiently.
Your email address will not be published. Comments are moderated.
0 Comments on This Post
Leave a Reply
Comments (0)
Spread the Word!
Join Our Developer Community!
Get weekly coding tips, tool updates, and exclusive tutorials straight to your inbox.
Request a Tool
×