介绍:
Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上.
安装:
composer require guzzlehttp/guzzle
基础:
use GuzzleHttp\Client;
$client = new Client();
$request = $client->request('GET', 'https://www.google.com/');
$headers = $request->getHeaders();
$contents = $request->getBody()->getContents();
进阶:
模拟POST提交表单
$options = [
'form_params' => [
'username' => 'zhangsan',
'password' => '123456'
]
];
$client->request('POST', 'https://www.google.com/', $options);
自定义headers进行请求
$options = [
'headers' => [
'Authorization' => 'access_token',
'user-agent' => 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'x-requested-with' => 'XMLHttpRequest'
];
];
$client->request('POST', 'https://www.google.com/', $options);
携带cookie进行请求:
use GuzzleHttp\Cookie\CookieJar;
$jar = new CookieJar();
$cookies = [
'sessionid' => 'sessionid',
'user_id=' => 'user_id'
];
$jar->fromArray($cookies, 'https://www.google.com/');
$options = [
'cookies' => $jar;
];
$client->request('POST', 'https://www.google.com/', $options);
文档地址:https://docs.guzzlephp.org/en/stable/index.html