【问题标题】:How to access RESTful API via PHP如何通过 PHP 访问 RESTful API
【发布时间】:2011-12-21 09:49:15
【问题描述】:

我对 PHP 和使用 RESTful API 的整个事情还是很陌生。 我现在想做的就是成功发出一个普通的 HTTP GET 请求 OpenStreetMap API

我正在使用simple PHP REST client by tcdent,我基本上了解它的功能。我在 OSM 中获取当前变更集的示例代码是:

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

当我在浏览器中输入 URL“http://api.openstreetmaps.org/api/0.6/changesets”时,它会传递 XML 文件。但是,通过此 PHP 代码,它会返回 OSM 404 File not Found 页面。

我想这是一个相当愚蠢的 PHP 新手问题,但我看不出我缺少什么,因为我对所有这些客户端-服务器端进程等知之甚少。

感谢您的帮助!

【问题讨论】:

    标签: php rest get openstreetmap


    【解决方案1】:

    好的,问题显然是“格式”=>“xml”规范。 没有它并在 SimpleXMLElement 的帮助下(感谢 Martin),我现在可以正确加载 XML 数据:

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

    虽然这不是一种非常灵活的方法,因为它仅适用于 XML 响应,但目前已经足够了,并且是从 OSM API 开始的一个好点。

    感谢您的帮助!

    【讨论】:

      【解决方案2】:

      使用卷曲。见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);

      【讨论】:

      • 谢谢,但我的 RestClient 类在内部使用 curl。我发布的代码与 tcdent 在 git 网站上关于如何使用他的客户端的建议非常接近。我基本上只将格式从 JSON 更改为 XML,因为 OSM API 总是返回 XML。所以可能是格式问题?!
      猜你喜欢
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 2017-02-22
      • 2014-09-01
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      相关资源
      最近更新 更多