BrowserKit是模拟浏览器行为,让你能够程序化地制造请求、对链接的点击以及表单提交。
安装
composer require symfony/browser-kit
使用方法
declare(strict_types=1);
namespace app;
use Symfony\Component\BrowserKit\HttpBrowser;
use Symfony\Component\DomCrawler\Crawler;
class Http
{
/**
* 发起请求
* @access public
* @param string $_method 请求类型 GET|POST
* @param string $_uri 请求地址 http://xxx
* @return bool
*/
public function request(string $_method, string $_uri): bool
{
// 实例化
$client = new HttpBrowser;
$client->request($_method, $_uri, [], [], [
// 这里设置请求参数
'HTTP_HOST' => parse_url($_uri, PHP _URL_HOST),
'HTTP_USER_AGENT' => Request::header('user_agent'),
'HTTP_REFERER' => parse_url($_uri, PHP _URL_SCHEME) . '://' . parse_url($_uri, PHP _URL_HOST) . '/',
'HTTP_ACCEPT' => Request::header('accept'),
'HTTP_ACCEPT_LANGUAGE' => Request::header('accept_language'),
'HTTP_CONNECTION' => Request::header('connection'),
]);
// 请求失败
if (200 !== $this->client->getInternalResponse()->getStatusCode()) {
return false;
}
// 获得HTML文档内容
$this->result = $this->client->getInternalResponse()->getContent();
// 检查字符编码
if (preg_match('/charset=["\']?([\w\-]{1,})["\']?/si', $this->result, $charset)) {
$charset = strtoupper($charset[1]);
if ($charset !== 'UTF-8') {
$charset = 0 === stripos($charset, 'GB') ? 'GBK' : $charset;
$this->result = @iconv($charset, 'UTF-8//IGNORE', (string) $this->result);
$this->result = preg_replace_callback('/charset=["\']?([\w\-]{1,})["\']?/si', function ($matches) {
return str_replace($matches[1], 'UTF-8', $matches[0]);
}, $this->result);
}
}
return htmlspecialchars($this->result, ENT_QUOTES);
}
}