我正在尝试连接到一个RESTful Web服务,但是在发送PUT和DELETE数据时遇到了一些问题。使用cURL时,PUT需要发送一个文件,而DELETE是比较奇怪的。我完全有能力使用PHP的socket支持编写客户端并自己编写HTTP头,但我想知道您是否曾经使用过或看到过用于PHP的REST client?
事实证明,Zend_Rest_Client根本不是REST客户端 - 例如,它不支持PUT和DELETE方法。在尝试将其强行与实际的RESTful服务配合使用后,我感到厌烦,并为PHP编写了一个正确的REST客户端:
http://github.com/educoder/pest
我还需要加入一些东西,但如果得到采用,我会再做更多的工作。
以下是使用OpenStreetMap REST服务的示例:
<?php
/**
* This PestXML usage example pulls data from the OpenStreetMap API.
* (see http://wiki.openstreetmap.org/wiki/API_v0.6)
**/
require_once 'PestXML.php';
$pest = new PestXML('http://api.openstreetmap.org/api/0.6');
// Retrieve map data for the University of Toronto campus
$map = $pest->get('/map?bbox=-79.39997,43.65827,-79.39344,43.66903');
// Print all of the street names in the map
$streets = $map->xpath('//way/tag[@k="name"]');
foreach ($streets as $s) {
echo $s['v'] . "\n";
}
?>
目前它使用curl,但是我可能会在未来将其切换到HTTP_Request或HTTP_Request2。
更新:看起来很多人已经加入了这个项目。感谢GitHub上的贡献者,Pest现在支持HTTP身份验证和许多其他功能。
我写了一个名为 Guzzle 的 PHP HTTP 客户端。Guzzle 是一个用于构建 REST Web 服务客户端的 HTTP 客户端和框架。您可以在其 网站 上找到有关 Guzzle 的更多信息,或直接访问 github 源代码: https://github.com/guzzle/guzzle
Guzzle 提供了大多数 HTTP 客户端提供的好处(更简单的接口、所有的 HTTP 方法以及查看请求/响应),但还提供了其他高级功能:
唯一的缺点:需要 PHP 5.3.3。
我倾向于使用PHP内置的cURL支持。 CURLOPT_CUSTOMREQUEST
选项允许您执行PUT
/DELETE
等操作。
<?php
$url ="http://example.com";
$data = "The updated text message";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); //for updating we have to use PUT method.
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
?>
<?php
$url ="http://example.com/categoryid=xx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
?>
我很久以前就一直找不到优雅的解决方案,也不喜欢cURL实现,于是自己想出了一个方案。它支持HTTP身份验证、重定向、PUT等,因为它依赖于pecl http模块。
这个实现很好而且简单,易于扩展。
更多信息可以在这里找到:
我在使用Zend Rest Client时取得了很好的成功。
重新提起这个话题,我发现这个库https://github.com/Respect/Rest/非常容易使用,但是网上的示例很少:
require_once 'bootstrap.php';
require_once 'Respect/Rest/Router.php';
require_once 'Respect/Rest/Request.php';
use Respect\Rest\Router;
$router->post('/myApp/', function() {
$data_back = json_decode(file_get_contents('php://input'));
// var_dump($data_back);
return json_encode($data_back);
});
$router->get('/myApp/*', function($id = null) {
$json = json_encode(MyService::getInstance()->list());
return utf8_encode($json);
});
$router->put('/myApp/*', function($id = null) {
return 'Update: ' . $id;
});
$router->delete('/myApp/*', function($id = null) {
return 'Delete: ' . $id;
});