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!!! 😎
2 Comments
Pinix · July 20, 2014 at 9:42 PM
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
Upcoming Movie Trailers Thanks to Apple & YouTube | Chris West's Blog · July 10, 2014 at 4:12 PM
[…] little bit ago in this article I talked about being able to convert XML to JSON(P). I finally got around to making a page which […]