如何通过 PHP 访问 RESTful API

How to access RESTful API via PHP(如何通过 PHP 访问 RESTful API)
本文介绍了如何通过 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)