BrowserKit是模拟浏览器行为,让你能够程序化地制造请求、对链接的点击以及表单提交。
安装
composerrequiresymfony/browser-kit
使用方法
declare(strict_types=1);
namespaceapp;
useSymfony\Component\BrowserKit\HttpBrowser;
useSymfony\Component\DomCrawler\Crawler;
class Http
{
/**
*发起请求
*@accesspublic
*@param string$_method请求类型GET|POST
*@param string$_uri请求地址http://xxx
*@returnbool
*/
publicfunctionrequest(string$_method,string$_uri):bool
{
// 实例化
$client=newHttpBrowser;
$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()){
returnfalse;
}
//获得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){
returnstr_replace($matches[1],'UTF-8',$matches[0]);
},$this-result);
}
}
returnhtmlspecialchars($this-result,ENT_QUOTES);
}
}