许多同学在第一次使用curl的时候感觉一个头两个大(包括我在内),看着这一条条的curl_setopt函数完全摸不着头脑,不过在你花10分钟看了我的介绍后相信你以后也能轻松戏耍php的curl了
首先,请看一个curl代码(花10秒钟,略看一遍,然后跳到后文)
1 php 2 $data = [...]; 3 $tucurl = curl_init(); 4 curl_setopt($tucurl, curlopt_url, https://example.com/path/for/soap/url/); 5 curl_setopt($tucurl, curlopt_port , 443); 6 curl_setopt($tucurl, curlopt_verbose, 0); 7 curl_setopt($tucurl, curlopt_header, 0); 8 curl_setopt($tucurl, curlopt_sslversion, 3); 9 curl_setopt($tucurl, curlopt_sslcert, getcwd() . /client.pem); 10 curl_setopt($tucurl, curlopt_sslkey, getcwd() . /keyout.pem); 11 curl_setopt($tucurl, curlopt_cainfo, getcwd() . /ca.pem); 12 curl_setopt($tucurl, curlopt_post, 1); 13 curl_setopt($tucurl, curlopt_ssl_verifypeer, 1); 14 curl_setopt($tucurl, curlopt_returntransfer, 1); 15 curl_setopt($tucurl, curlopt_postfields, $data); 16 curl_setopt($tucurl, curlopt_httpheader, array(content-type: text/xml,soapaction: \/soap/action/query\, content-length: .strlen($data))); 17 18 $tudata = curl_exec($tucurl); 19 if(!curl_errno($tucurl)){ 20 $info = curl_getinfo($tucurl); 21 echo 'took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url']; 22 } else { 23 echo 'curl error: ' . curl_error($tucurl); 24 } 25 26 curl_close($tucurl); 27 echo $tudata; 28 ?>
wtf,这到底是在做什么?
想要学会这种“高端”的用法吗?
首先,相信你肯定知道网址大部分是由http开头的,那是因为他们需用通过http(超文本传送协议 http-hypertext transfer protocol)来进行数据传输,但是传输数据不是简单的将一句hello传到服务器上就搞定的事情,发送者为了方便接受者理解发送者的实际意图以及知道发送人到底是何许人也,发送者往往要将许多额外信息一并发给接受者,就像寄信人需要在信件外套一个信封一样,信封上写着各种发信人的信息。所有的这些最终合并成了一个叫做报文(message)的玩意,也就构成了整个互联网的基础。
curl的工作就是通过http协议发送这些message (php的libcurl目前还支持https、ftp、telnet等其他协议)
现在再看代码,实际上代码只做了五件事情
curl_init()初始化curl curl_setopt()设置传输数据和参数 curl_exec()执行传输并获取返回数据 curl_errono()返回错误码 curl_close()关闭curl 下面给出使用get和post方法如何抓取和提交任意页面的数据
1 php 2 //初始化 3 $curl = curl_init(); 4 //设置url 5 curl_setopt($curl, curlopt_url, 'http://www.baidu.com'); 6 //设置返回获取的输出为文本流 7 curl_setopt($curl, curlopt_returntransfer, true); 8 //执行命令 9 $data = curl_exec($curl);10 //关闭url请求11 curl_close($curl);12 //显示获得的数据13 print_r($data);14 ?>15 16 php17 //初始化18 $curl = curl_init();19 //设置url20 curl_setopt($curl, curlopt_url, 'http://www.baidu.com');21 //设置返回获取的输出为文本流22 curl_setopt($curl, curlopt_returntransfer, true);23 //设置post方式提交24 curl_setopt($curl, curlopt_post, 1);25 //设置post数据26 curl_setopt($curl, curlopt_postfields, array(data=>value);27 //执行命令28 $data = curl_exec($curl);29 //关闭url请求30 curl_close($curl);31 //打印数据32 print_r($data);33 ?>
感兴趣的同学还可以参考php官方文档,学习更多curl用法
2楼ronaldo7你能post数据到baidure: 深蓝的镰刀@ronaldo7,举个栗子吧1楼安度你和深蓝的右手什么关系re: 深蓝的镰刀@安度,我记得没错他应该是专注游戏引擎的大神吧
