PHP版的requests,和Python版requests很像,不过有部分功能还不太完善
文档: https://requests.ryanmccue.info/
安装
composer require rmccue/requests
使用示例
<?php
require __DIR__ . '/../vendor/autoload.php';
$response = Requests::get('http://httpbin.org/get');
var_dump($response->status_code);
// int(200)
var_dump($response->success);
// bool(true)
print_r($response->body);
请求结果
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"Host": "httpbin.org",
"Referer": "http://httpbin.org/get",
"User-Agent": "php-requests/1.8.1",
"X-Amzn-Trace-Id": "Root=1-60c2c3c7-1d58e3595266f3c26f4d74c5"
},
"origin": "61.48.42.101",
"url": "http://httpbin.org/get"
}
添加查询参数
$params = [
'name'=> 'Tom',
'age' => 23
];
$url = $url . '?' . http_build_query($params);
对结果进行处理
// 转换为关联数组
if ($response->success) {
$data = json_decode($response->body, true);
}
发送json数据
<?php
require 'vendor/autoload.php';
$url = 'http://httpbin.org/post';
$header = [
'Content-Type'=> 'application/json;charset=UTF-8'
];
$data = [
'name'=> 'Tom',
'age'=> 23
];
$response = Requests::post($url, $header, json_encode($data));
print_r($response->body);
返回结果
{
"args": {},
"data": "{\"name\":\"Tom\",\"age\":23}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"Content-Length": "23",
"Content-Type": "application/json;charset=UTF-8",
"Host": "httpbin.org",
"Referer": "http://httpbin.org/post",
"User-Agent": "php-requests/1.8.1",
"X-Amzn-Trace-Id": "Root=1-61e2353f-1dfbdda773c67065782332d6"
},
"json": {
"age": 23,
"name": "Tom"
},
"origin": "1.202.253.34",
"url": "http://httpbin.org/post"
}