Recipe 14.1. Calling a REST Method


14.1.1. Problem

You want to make a REST request.

14.1.2. Solution

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); ?>

14.1.3. Discussion

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. The ins and outs of these options are covered in the beginning of Chapter 13.

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. It's covered in Recipe 12.3. However, there are times when you may want to use other extensions, such as DOM , XMLReader , or even XSLT. These are covered throughout Chapter 12.

14.1.4. See Also

Chapter 13 goes into detail on retrieving remote URLs; Recipe 15.1 for more on serving REST requests.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net