如何通过PHP访问RESTful API [英] How to access RESTful API via PHP

查看:45
本文介绍了如何通过PHP访问RESTful API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于PHP以及使用RESTful API的整个工作,我还很陌生.目前,我要做的只是成功向发出纯HTTP GET请求 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;
?>

当我在浏览器中输入URL"http://api.openstreetmaps.org/api/0.6/changesets"时,它将传递XML文件.但是,通过此PHP代码,它将返回找不到OSM 404文件"页面.

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 =新的SimpleXMLElement($ curl_response);

$xml = new SimpleXMLElement($curl_response);

这篇关于如何通过PHP访问RESTful API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆