How to access RESTful API via PHP

Matthias Loeks picture Matthias Loeks · Nov 3, 2011 · Viewed 42.4k times · Source

I'm pretty new to PHP and the whole thing of working with RESTful APIs. All I want to do at the moment is successfully issue a plain HTTP GET request to the OpenStreetMap API.

I am using the simple PHP REST client by tcdent and I basically understand it's functionality. My example code for getting the current Changesets in OSM is:

<?php
 include("restclient.php");

 $api = new RestClient(array(
     'base_url' => "http://api.openstreetmaps.org/", 
     'format' => "xml")
 );
 $result = $api->get("api/0.6/changesets");

 if($result->info->http_code < 400) {         
     echo "success:<br/><br/>";         
 } else {
     echo "failed:<br/><br/>";
 }
 echo $result->response;
?>

When I enter the URL "http://api.openstreetmaps.org/api/0.6/changesets" in the browser, it delivers the XML file. However, through this PHP code it returns the OSM 404 File not Found page.

I guess this is a rather stupid PHP-newbie question but I cannot see what I am missing, since I do not know much (yet) about all these client-server side processes etc.

Thanks for your help!

Answer

Martin Stein picture Martin Stein · Nov 3, 2011

Use curl. See http://www.lornajane.net/posts/2008/using-curl-and-php-to-talk-to-a-rest-service

   $service_url = 'http://example.com/rest/user/';
   $curl = curl_init($service_url);
   $curl_post_data = array(
        "user_id" => 42,
        "emailaddress" => '[email protected]',
        );
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($curl, CURLOPT_POST, true);
   curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
   $curl_response = curl_exec($curl);
   curl_close($curl);

$xml = new SimpleXMLElement($curl_response);