How to access RESTful API via PHP

拜拜、爱过 提交于 2021-02-15 09:04:26

问题


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!


回答1:


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" => 'lorna@example.com',
        );
   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);




回答2:


OK, the problem was apparently the 'format' => "xml" specification. Without it and with the help of SimpleXMLElement (thanks Martin), I am now getting the XML data loaded properly:

<?php
   include("restclient.php");
   $api = new RestClient(); 
   $result = $api->get("http://api.openstreetmap.org/api/capabilities");
   $code = $result->info->http_code;
   if($code == 200) {
       $xml = new SimpleXMLElement($result->response);
       echo "Loaded XML, root element: ".$xml->getName();
   } else {
       echo "GET failed, error code: ".$code;
   }
?>

Although this is not a very flexible approach since it works only for XML responses, it is enough for the moment and a good point to start with the OSM API.

Thanks for your help!



来源:https://stackoverflow.com/questions/7999323/how-to-access-restful-api-via-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!