Simple XML to JSON with PHP


Hello all, it’s been a while since I have blogged anything, been extremely busy with personal events in my life. So to get back into the swing of things I am going to KISS this post. I recently needed to convert XML to JSON in PHP. Thankfully, PHP has built in functionality to handle precisely this task. First we need to get contents of the XML file, we need to use _file\_get\_contents()_ and pass it the URL to the XML file. We remove the newlines, returns and tabs.
$fileContents = file_get_contents($url);

$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
Next I replace double quotes with single quotes and trim leadign and trailing spaces, this helps to ensure the simple XML function can parse the XML appropriately. Then we call the _simplexml\_load\_string()_ function.
$fileContents = trim(str_replace('"', "'", $fileContents));

$simpleXml = simplexml_load_string($fileContents);
The final step we need is to convert the XML to JSON, for that we will use the _json_encode()_ function.
$json = json_encode($simpleXml);</pre>


That’s it! All together now:

<?php

class XmlToJson {

	public function Parse ($url) {

		$fileContents= file_get_contents($url);

		$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);

		$fileContents = trim(str_replace('"', "'", $fileContents));

		$simpleXml = simplexml_load_string($fileContents);

		$json = json_encode($simpleXml);

		return $json;

	}

}

?>

Now if we want to utilize our creation we can create a file which uses the class we created above, assuming we store the XmlToJson class in a file named XmlToJson.php. We can create a file for a specific XML web service, include our class and call it XmlToJson::Parse($url). Just for fun we’ll point to the XML for the NFL scorestrip.

<?php

include 'XmlToJson.php';

print XmlToJson::Parse("http://www.nfl.com/liveupdate/scorestrip/ss.xml");

?>

Now we can call our new file, say we name it getNflDataAsJson.php, it will return the converted JSON. Calling it from jQuery below:

$.getJSON('getNflDataAsJson.php', function(data) { 
	//do something
});

Thats all I’ve got, let me know if you have any questions, things you would do differently or general comments.

Thanks much!

</article>
Serving Images from an Image Controller