Convert XML to JSON Like a Pro in PHP!

Serghei Pogor
6 min readMar 21, 2024

Ready to master the art of XML to JSON conversion in PHP? Look no further! In this guide, we’ll unveil the secrets that will have you converting XML to JSON like a pro in no time. Say goodbye to complexity and hello to effortless data transformation. Let’s dive in!

What is XML

XML, or eXtensible Markup Language, is a widely-used format for storing and exchanging structured data. It’s like a customizable language for describing information. Imagine you have a document with various sections, each labeled with specific tags, like <book> or <person>. Inside these tags, you can have data like titles, names, or even nested sections. XML is commonly used in web services, configuration files, and data storage because it's flexible and can represent complex structures.

<bookstore>
<book category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<price>10.99</price>
</book>
<book category="non-fiction">
<title>Thinking, Fast and Slow</title>
<author>Daniel Kahneman</author>
<price>15.99</price>
</book>
</bookstore>

JSON

JSON, short for JavaScript Object Notation, is a lightweight data-interchange format. It’s similar to XML but more concise and easier for both humans and machines to read and write. JSON represents data as key-value pairs, enclosed in curly braces {}, making it resemble objects in JavaScript. For example, you might have "name": "John" or "age": 30. Arrays are also supported, allowing for lists of items. JSON is commonly used in web APIs and AJAX requests due to its simplicity and compatibility with JavaScript.

{
"books": [
{
"category": "fiction",
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"price": 10.99
},
{
"category": "non-fiction",
"title": "Thinking, Fast and Slow",
"author": "Daniel Kahneman",
"price": 15.99
}
]
}

Let’s suppose a scenario: You are a developer tasked with integrating a third-party weather API into a web application. The weather API provides data in XML format, but your web application is designed to handle JSON data for easy manipulation and presentation.

Your goal is to seamlessly integrate the weather data from the API into your web application’s interface, ensuring that users can easily access and view current weather conditions, forecasts, and other relevant information.

To achieve this, you need to develop a solution that fetches weather data from the API, converts it from XML to JSON format, and then processes and displays it within your web application’s user interface.

PHP Converting XML to JSON

In PHP, converting XML data to JSON format is a common task, especially when dealing with APIs or data sources that provide information in XML but need to be consumed in JSON by the application. Let’s explore how to accomplish this conversion effortlessly.

PHP Converting XML to JSON

📝 Parsing XML Data

First, we need to parse the XML data to extract the information we want to convert to JSON. PHP provides several built-in functions for XML parsing, such as SimpleXML and DOMDocument.

$xmlString = file_get_contents('example.xml');
$xml = simplexml_load_string($xmlString);

In this example, we use simplexml_load_string() to parse an XML string into a SimpleXMLElement object.

🔃 Converting XML to JSON

Once we have the XML data parsed, we can convert it to JSON format. PHP’s json_encode() function can be used to accomplish this.

$json = json_encode($xml);

By passing the SimpleXMLElement object to json_encode(), PHP automatically converts it to a JSON string.

🛠️ Handling Errors

It’s essential to handle errors that may occur during the conversion process. For example, if the XML data is malformed or contains unexpected elements, the conversion may fail.

if ($json === false) {
echo "Error converting XML to JSON: " . json_last_error_msg();
}

Using json_last_error_msg(), we can retrieve the last error message if the conversion fails.

Suppose we have an XML file containing information about products:

<products>
<product>
<name>Widget A</name>
<price>19.99</price>
</product>
<product>
<name>Widget B</name>
<price>24.99</price>
</product>
</products>

We can convert this XML data to JSON using the above PHP code:

$xmlString = file_get_contents('products.xml');
$xml = simplexml_load_string($xmlString);
$json = json_encode($xml);
echo $json;

This will output the following JSON:

{
"product": [
{
"name": "Widget A",
"price": "19.99"
},
{
"name": "Widget B",
"price": "24.99"
}
]
}

By following these simple steps, you can easily convert XML data to JSON in PHP, enabling seamless integration with your applications. 🚀

PHP Converting JSON to XML

In PHP, converting JSON data to XML format is another common task, especially when dealing with APIs or systems that require XML input but provide JSON output. Let’s explore how to achieve this conversion efficiently.

PHP Converting JSON to XML

🔍 Decoding JSON Data

First, we need to decode the JSON data to extract the information we want to convert to XML. PHP’s json_decode() function can be used for this purpose.

$jsonString = '{"product": [{"name": "Widget A", "price": "19.99"}, {"name": "Widget B", "price": "24.99"}]}';
$json = json_decode($jsonString);

In this example, we decode a JSON string into a PHP object using json_decode().

🔃 Converting JSON to XML

Once we have the JSON data decoded, we can convert it to XML format. PHP provides various methods for creating XML documents, such as the DOM extension.

$dom = new DOMDocument('1.0', 'UTF-8');
$products = $dom->createElement('products');
$dom->appendChild($products);

foreach ($json->product as $item) {
$product = $dom->createElement('product');
foreach ($item as $key => $value) {
$product->appendChild($dom->createElement($key, $value));
}
$products->appendChild($product);
}

$xml = $dom->saveXML();

In this code snippet, we create a new XML document using DOMDocument and iterate over the JSON data to create XML elements based on the key-value pairs.

🛠️ Handling Errors

As with converting XML to JSON, it’s essential to handle errors that may occur during the conversion process.

if ($xml === false) {
echo "Error converting JSON to XML";
}

Suppose we have the following JSON data representing product information:

{
"product": [
{
"name": "Widget A",
"price": "19.99"
},
{
"name": "Widget B",
"price": "24.99"
}
]
}

By following these steps, you can easily convert JSON data to XML in PHP, enabling seamless integration with systems or applications that require XML input. 🌟

PHP Convert XML <> JSON: When to NOT Convert

As a PHP developer, you’ll encounter numerous scenarios where converting XML to JSON is advantageous. However, it’s crucial to recognize situations where such conversion might not be the best approach. Let’s explore when it’s prudent to avoid converting XML to JSON.

Preserving Data Integrity

In some cases, the structure and semantics of the XML data are critical for maintaining data integrity. Converting XML to JSON may result in loss of information or misinterpretation of the original data structure. For instance, XML attributes or namespaces may not be accurately represented in JSON format, leading to data loss.

// Example of preserving XML attributes during conversion
$xmlString = '<book isbn="123456"><title>PHP Cookbook</title></book>';
$xml = simplexml_load_string($xmlString);
$json = json_encode($xml, JSON_FORCE_OBJECT);

Complex XML Structures

XML documents with complex hierarchical structures or nested elements may not translate well into JSON format. Attempting to convert such XML data to JSON could result in overly nested or convoluted JSON objects, making it challenging to parse and manipulate the data effectively.

// Example of handling complex XML structures during conversion
$xmlString = '<employees>
<employee>
<id>1</id>
<name>John Doe</name>
<department>
<name>Engineering</name>
<manager>
<name>Jane Smith</name>
<email>jane@example.com</email>
</manager>
</department>
</employee>
<employee>
<id>2</id>
<name>Alice Johnson</name>
<department>
<name>Marketing</name>
<manager>
<name>David Brown</name>
<email>david@example.com</email>
</manager>
</department>
</employee>
</employees>';

// Load XML string into SimpleXMLElement object
$xml = simplexml_load_string($xmlString);

// Convert SimpleXMLElement object to array
$array = json_decode(json_encode($xml), true);

// Convert array to JSON string
$json = json_encode($array);

echo $json;

Compatibility Requirements

If the target system or application strictly requires XML input, converting XML to JSON would be counterproductive. It’s essential to adhere to the specifications and requirements of the receiving system to ensure seamless integration and data exchange.

// Example of submitting XML data to an API that only accepts XML
$xmlString = '<request><data>Hello, World!</data></request>';

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/endpoint');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlString);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/xml',
'Content-Length: ' . strlen($xmlString)
]);

// Execute cURL request
$response = curl_exec($ch);

// Check for errors
if(curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
// Output API response
echo $response;
}

// Close cURL session
curl_close($ch);

By recognizing these scenarios, you can make informed decisions about whether to convert XML to JSON in your PHP applications. It’s crucial to prioritize data integrity, handle complex XML structures effectively, and ensure compatibility with the target systems. 🚫🔀

🔔 Click “Subscribe” to catch more coding fun.
👏🏻 Love it? Give a big clap.
💬 Got a cool idea or funny coding joke? Drop it in the comments.

Share this with your coding buddies who’d love a good laugh too!

PHP is like a master translator, switching between JSON and XML without a hitch, so your data always talks the right talk, no matter where it goes.

Thanks for hanging out and reading. You rock! 🚀

--

--