2011-11-03 61 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開始的一個很好的觀點。

感謝您的幫助!