For a few months now I have been playing around with some of the cool API's listed at ProgrammableWeb. As fun as it is to use these web services it's not fun trying to get your head around the Request/Response aspects of web http requests. When it comes to .NET and Web Services its is pretty simple because VisualStudio does most of the dirty work and gives you back a class to program against. But when it comes to PHP and Web Services you are pretty much on your own.
In this short hack I am doing to demonstrate how to make a Web Service request using REST.
There are two methods you can use in PHP for making a REST request: file_get_contents() and cURL.
For some reason my php_info() indicates that file_get_contents is enabled but I keep getting access errors so I'll focus on the second method, cURL.
Before I get into the code I must state that my solution was inspired by the recently updated book PHP Cookbook 2nd Ed.
For this example I'll use Yahoo! to search for info about U2.
Parsing the REST Request Using SimpleXml
This requires PHP5.
The code for this is very simple and is less than 20 lines long. But in that 20 lines we will create a URL to the Yahoo Search API with an API Key and a search term all neatly encoded.
Next we instantiate cURL and set some options then execute the request and get back a response in XML.
Once we've got the XML Response we pass it to the simplexml_load_string function which will return a SimpleXMLElement object class.
From there we will loop over each Result in the object class and output the results (Title, Summary & Link) as html.
You can run this code by pasting it into a page and the passing the page a url prameter like this:
index.php?keyword=U2
Congratulations you have now completed a REST request using PHP.
A some time after the Virginia Tech massacre:
http://online-freesearch.com/design/index.html