Friday, December 10, 2010

You want to make a REST request and consume a Web Service

For Creating a REST Web Service , See my previous Post
For Consuming a Web Service , Use file_get_contents( ):
<?php
$base = 'http://music.example.org/search.php';
$params = array('composer' => 'beethoven',
'instrument' => 'cello');
$url = $base . '?' . http_build_query($params);
$response = file_get_contents($url);
?>

Or use cURL:
<?php
$base = 'http://music.example.org/search.php';
$params = array('composer' => 'beethoven',
'instrument' => 'cello');
$url = $base . '?' . http_build_query($params);
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($c);
curl_close($c);
?>

REST is a style of web services in which you make requests using HTTP methods such as get and post, and the method type tells the server what action it should take. For example, get tells the server you want to retrieve existing data, whereas post means you
want to update existing data. The server then replies with the results in an XML document that you can process. The brilliance of REST is in its simplicity and use of existing standards. PHP’s been
letting you make HTTP requests and process XML documents for years, so everything you need to make and process REST requests is old hat.
There are many ways to execute HTTP requests in PHP, including
file_get_contents( ), the cURL extension, and PEAR packages.
Once you’ve retrieved the XML document, use any of PHP’s XML extensions to process it. Given the nature of REST documents, and that you’re usually familiar with the schema of the response, the SimpleXML extension is often the best choice.

No comments:

Post a Comment