如何通过 PHP 访问 RESTful API
我对 PHP 以及使用 RESTful API 的整个过程还很陌生。 我现在想要做的就是成功发出一个简单的 HTTP GET 请求 OpenStreetMap API。
我正在使用 tcdent 的简单 PHP REST 客户端,我基本上了解它的功能。我在 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 新手问题,但我看不出我错过了什么,因为我(还)对所有这些客户端服务器端进程等了解不多。
感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用卷曲。请参阅 http:// www.lornajane.net/posts/2008/using-curl-and-php-to-talk-to-a-rest-service
$xml = new SimpleXMLElement($curl_response);
Use curl. See http://www.lornajane.net/posts/2008/using-curl-and-php-to-talk-to-a-rest-service
$xml = new SimpleXMLElement($curl_response);
好吧,问题显然是“格式”=>; “xml”规范。
如果没有它,在 SimpleXMLElement 的帮助下(感谢 Martin),我现在可以正确加载 XML 数据:
虽然这不是一个非常灵活的方法,因为它仅适用于 XML 响应,但目前已经足够了,并且是一个很好的点从 OSM API 开始。
感谢您的帮助!
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:
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!