How to access RESTful API via PHP(如何通过 PHP 访问 RESTful API)
问题描述
我对 PHP 以及使用 RESTful API 的整个过程非常陌生.我现在想要做的就是成功地向OpenStreetMap API.
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.
我正在使用 tcdent 提供的简单 PHP REST 客户端,我基本上了解它的功能.我在 OSM 中获取当前变更集的示例代码是:
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;
?>
当我在浏览器中输入 URLhttp://api.openstreetmaps.org/api/0.6/changesets"时,它会提供 XML 文件.但是,通过此 PHP 代码,它返回 OSM 404 File not Found 页面.
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.
我想这是一个相当愚蠢的 PHP 新手问题,但我看不出我遗漏了什么,因为我对所有这些客户端 - 服务器端进程等知之甚少.
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.
感谢您的帮助!
推荐答案
使用 curl.见 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);
$xml = new SimpleXMLElement($curl_response);
这篇关于如何通过 PHP 访问 RESTful API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!