2011-11-03 140 views
10

我对PHP非常陌生,并且对使用RESTful APIs的工作很感兴趣。 我现在想要做的就是成功地发出一个普通的HTTP GET请求到 OpenStreetMap API如何通过PHP访问RESTful 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,新手的问题,但我不能看到我缺少什么,因为我不知道很多(但)对所有这些客户端 - 服务器端进程等

谢谢您帮帮我!

回答

12

使用卷曲。见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 =新的SimpleXMLElement($ curl_response);

+0

谢谢,但我的RestClient类内部使用curl。我发布的代码与gc-website上关于如何使用其客户端的建议非常接近。由于OSM API始终返回XML,因此我基本上只将格式从JSON更改为XML。所以也许它可能是一个格式问题?! – matze09

4

好的,问题显然是'format'=>“xml”规范。 没有它,用的SimpleXMLElement(感谢马丁)的帮助下,我现在得到正确加载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开始的一个很好的观点。

感谢您的帮助!