php - curl
curl 是客户端向服务器请求资源的工具
查看windows和linux查看是是否安装curl (如果未安装,百度关键词: php windows curl php linux curl )
windows:cmd -> php -i
linux : php -i | grep cURL
PHP使用基本使用curl
简单实验:
$curl = curl_init('http://www.baidu.com'); curl_exec($curl); curl_close($curl); cmd : cd /d D:\wamp64\www(执行文件路径) php -f index.php (执行PHP文件) php -f index.php > index.html (写入指定文件中)
简单实验2:在网上下载一个网页并把内容中的“百度”替换为“屌丝”之后输出
关键点:url通过参数设置,CURLOPT_RETURNTRANSFER 设置为 true 只是下载不去编辑和打印
$curlobj = curl_init();//初始化 curl_setopt($curlobj,CURLOPT_URL,"http://www.baidu.com"); // 设置访问链接 curl_setopt($curlobj,CURLOPT_RETURNTRANSFER,true); //执行之后不直接打印 $output = curl_exec($curlobj);//执行 curl_close($curlobj); // 关闭curl echo str_replace('百度','帅气',$output);
简单实验3:通过调用WebService查询北京的当天天气
$data = 'theCityName=北京'; $curlobj = curl_init(); curl_setopt($curlobj,CURLOPT_URL,'http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName'); curl_setopt($curlobj,CURLOPT_HEADER,0); curl_setopt($curlobj,CURLOPT_RETURNTRANSFER,1); curl_setopt($curlobj,CURLOPT_POST,1); curl_setopt($curlobj,CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36'); curl_setopt($curlobj,CURLOPT_POSTFIELDS,$data); curl_setopt($curlobj,CURLOPT_HTTPHEADER, array( "application/x-www-form-urlencoded; charset=utf-8", "Content-length: " . strlen($data) ) ); $rtn = curl_exec($curlobj); if(!curl_errno($curlobj)){ echo $rtn; }else{ echo 'Curl error : ' . curl_errno($curlobj); } curl_close($curlobj);