PHP – XML To JSON Proxy

Today I was looking for a way to easily pull in RSS feed data from Apple Trailers onto my site via AJAX. At first I was thinking about using jQuery to do it but then I got thinking about how cool it would be to have a PHP script that transforms any XML file into JSON. Thus, the following PHP script was written:

$json = json_encode(simplexml_load_string(file_get_contents($_GET['url'])));
if(isset($_GET['jsonp'])) {
  $json = "{$_GET['jsonp']}($json);";
}
echo $json;

Pretty cool, right?! The above five lines can be used to make a proxy which can convert XML to JSON or even JSONP. Let’s say I had this script at http://example.com/xml-to-json.php. With such a script in place one could simply pull the JSON version of the Apple Trailers RSS feed from http://example.com/xml-to-json.php?url=http%3A%2F%2Ftrailers.apple.com%2Ftrailers%2Fhome%2Frss%2Fnewtrailers.rss. The JSONP equivalent (using loadTrailers as the callback function) would be http://example.com/xml-to-json.php?url=http%3A%2F%2Ftrailers.apple.com%2Ftrailers%2Fhome%2Frss%2Fnewtrailers.rss&jsonp=loadTrailers. Believe it or not, it is really that easy!!! 8-)

2 thoughts on “PHP – XML To JSON Proxy”

  1. Hi,
    You got my attention by mencioning apple trailers.
    I’ve been looking at your code alot.

    I’m more of a designer myself and i’m trying to get the APPLE TRAILERS JSON via AJAX width JQuery and no luck so far :(

    Could you help me with your amazing skills? :) just a little script? maybe some simple php?

    Thanks for sharing

Leave a Reply

Your email address will not be published. Required fields are marked *


one × = 9

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">