How to Create an XML to JSON Proxy Server in PHP

Share this article

Key Takeaways

  • Creating an XML to JSON proxy server in PHP is a simple solution for retaining the benefits of XML data interchange while providing the ease of JSON in JavaScript. This server can process data, translating XML messages to JSON before they reach your JavaScript code.
  • The PHP script for the proxy server uses PHP’s cURL library to fetch content from the URL and pass it to a string. It then loads the returned string as a SimpleXMLElement object and returns a JSON-encoded message. If nothing is returned, an exception handler function outputs a JSON-encoded error flag.
  • The JavaScript component of the proxy server defines the remote URL to call, appends it to the PHP proxy address as a ‘url’ parameter, and passes it to the open() method of an XMLHttpRequest call. The XMLHttpRequest onreadystatechange handler then receives the data and converts the JSON string to a real JavaScript object.
Unless you’re new to this web development lark, you’ll know the ‘X’ in ‘AJAX’ stands for XML — eXtensible Markup Language. But you’re probably not using XML. If you are, you’d probably prefer not to. All the cool kids are using JSON or JSON-P: it has a smaller payload, is easier to use and faster to process. That’s not to say XML shouldn’t be used. It’s been around a long time and is well-supported by most languages — including JavaScript. If you’re sharing data between a variety of systems and platforms, XML is almost certainly the most practical choice. But that doesn’t ease your client-side coding efforts. Fortunately, there are a couple of solutions which allow you to retain the benefits of XML data interchange but provide the ease of JSON in JavaScript. In this article, we’re going to create an XML to JSON proxy server in PHP.

That Sounds Complicated?

Don’t worry, it’s not. In essence, a proxy sits between the client and server passing messages between the two. You’re probably sitting behind a proxy now — they’re used on the internet to cache data and reduce network traffic. However, they can also process data; we will create a simple PHP proxy which translates XML messages to JSON before they reach your JavaScript code.

Proxy Plan

Our system will:
  1. Send an Ajax request from JavaScript which calls the PHP proxy. It will pass a single encoded URL as a GET parameter named ‘url’.
  2. The proxy will fetch the contents of the passed URL as a string, parse it as XML and convert it to JSON.
  3. The JSON string will be returned to the calling JavaScript process.
If necessary, we could create a full REST-aware proxy which parsed POST, PUT and DELETE parameters. But this simple solution will be adequate for 99% of Ajax queries and it has a few other advantages:
  • It’s possible to call web services on foreign domains — that’s not always possible with a JavaScript-only solution.
  • If necessary, the proxy could strip unnecessary data from the message to reduce the payload.
  • We’ll require less JavaScript code and it will execute faster.

The PHP

PHP provides support for both XML and JSON so creating our proxy, xmlproxy.php, is reassuringly simple. That said, a lot can go wrong. Our script might fail, the remote service might go down, or the returned XML could be malformed. We don’t want PHP errors sent back to JavaScript so we’ll define an exception handler to hide them:

<?php
ini_set('display_errors', false);
set_exception_handler('ReturnError');
We now require two variables for the response ($r) and the passed URL ($url):

$r = '';
$url = (isset($_GET['url']) ? $_GET['url'] : null);
PHP’s cURL library is used to fetch content from the URL and pass it to string $r:

if ($url) {

	// fetch XML
	$c = curl_init();
	curl_setopt_array($c, array(
		CURLOPT_URL => $url,
		CURLOPT_HEADER => false,
		CURLOPT_TIMEOUT => 10,
		CURLOPT_RETURNTRANSFER => true
	));
	$r = curl_exec($c);
	curl_close($c);

}
Assuming something was returned, we’ll load it as a SimpleXMLElement object and return a JSON-encoded message:

if ($r) {
	// XML to JSON
	echo json_encode(new SimpleXMLElement($r));
}
If nothing was returned, we’ll call our exception handler function, ReturnError(), which outputs a JSON-encoded error flag:

else {
	// nothing returned?
	ReturnError();
}

// return JSON error flag
function ReturnError() {
	echo '{"error":true}';
}

The JavaScript

Our JavaScript must define the remote URL to call, e.g.

// example XML feed
var url = "http://domain.com/example.xml?status=123&date=2011-01-01";
The URL is appended to the PHP proxy address as a ‘url’ parameter and passed to the open() method of our XMLHttpRequest call (Ajax):

// AJAX request
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", "xmlproxy.php?url=" + escape(url), true);
xhr.send(null);
Finally, our XMLHttpRequest onreadystatechange handler receives the data and converts the JSON string to a real JavaScript object:

// handle response
function XHRhandler() {

	if (xhr.readyState == 4) {
	
		// parse response as JSON
		var json;
		if (JSON && JSON.parse) {
			json = JSON.parse(xhr.responseText);
		}
		else {
			eval("var json = " + xhr.responseText);
		}
		
		// do something with our returned JSON data...
		console.log(json);
		
		xhr = null;
	
	}

}
Please download the code, extract the files to your PHP-enabled web server, and open proxy.html in a browser.

A Note About XML Attribute Encoding

XML has a richer syntax than JSON and data can be encoded as elements or attributes — even with the same name, e.g.

<?xml version="1.0"?>
<statuses>
	<status id="one">
		<id>1</id>
	</status>
</statuses>
The PHP json_encode function translates attributes to a separate ‘@attributes’ object, i.e.

{
	"status": {
		"@attributes": { "id": "one" },
		"id": "1"
	}
}
I hope you find the code useful. It allows you to have your XML cake and consume it as JSON!

Frequently Asked Questions (FAQs) about PHP XML to JSON Conversion

What is the basic difference between XML and JSON formats?

XML (eXtensible Markup Language) and JSON (JavaScript Object Notation) are both popular data interchange formats. XML is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. It is often used for the representation of arbitrary data structures such as those used in web services. On the other hand, JSON is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999.

Why would I need to convert XML to JSON in PHP?

There could be several reasons to convert XML to JSON in PHP. One of the main reasons is that JSON is generally easier to work with and more efficient than XML. JSON is often used when data is sent from a server to a web page. It is “self-describing” and easy to understand. Moreover, JSON is faster and easier to parse than XML.

How can I convert XML to JSON using PHP?

PHP provides built-in functions to convert XML to JSON. You can use the simplexml_load_string() function to parse the XML data, and then use the json_encode() function to convert it into JSON format.

Can I convert XML attributes to JSON in PHP?

Yes, you can convert XML attributes to JSON in PHP. When you use the simplexml_load_string() function, it will include attributes in the resulting object. You can then convert this object to JSON using the json_encode() function.

What are the common errors I might encounter while converting XML to JSON in PHP?

Some common errors you might encounter include malformed XML, encoding issues, or problems with the XML structure. These can usually be resolved by checking the XML data for errors, ensuring it is properly encoded, and verifying that it is correctly structured.

How can I handle errors while converting XML to JSON in PHP?

PHP provides several functions to handle errors. You can use the libxml_get_errors() function to get an array of errors for the last XML parsing operation. You can then loop through this array to handle each error individually.

Can I convert XML to JSON in PHP without using any libraries?

Yes, you can convert XML to JSON in PHP without using any libraries. PHP provides built-in functions like simplexml_load_string() and json_encode() that you can use to convert XML to JSON.

How can I convert XML to JSON in PHP using libraries?

There are several libraries available that can simplify the process of converting XML to JSON in PHP. For example, you can use the xml2json library available on GitHub. This library provides a simple function to convert XML to JSON.

Can I convert XML to JSON in PHP for complex XML structures?

Yes, you can convert complex XML structures to JSON in PHP. The simplexml_load_string() function can handle complex XML structures, including nested elements and attributes. However, you may need to write additional code to handle specific complexities in your XML data.

How can I optimize the conversion of XML to JSON in PHP for large data sets?

If you are working with large XML data sets, you may need to optimize your code to avoid memory issues. One way to do this is by using a streaming parser, which processes the XML data in chunks rather than loading the entire data set into memory at once.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

ajaxHTML5 Dev CenterJavaScriptjsonPHPxml
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week