1. 使用curl,get获得数据
<?php $url = 'http://www.example.com'; //初始化一个 cURL 对象 $ch = curl_init(); //设置你需要抓取的URL curl_setopt($ch, CURLOPT_URL, $url); // 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //是否获得跳转后的页面 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $data = curl_exec($ch); curl_close($ch); echo $data; ?>
2. 使用curl,post获得数据
<?php function curl_post($url, $arr_data){ $post_data = http_build_query($url_data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFLELDS, $post_data); $data = curl_exec($ch); curl_close($ch); echo $data; } $arr_post = array( 'name'=>'test_name', 'age' => 1 ); curl_post("http://www.explame.com/", $arr_post); ?>
3. 使用代理抓取页面
为什么要使用代理进行抓取呢?以google为例吧,如果去抓google的数据,短时间内抓的很频繁的话,你就抓取不到了。google对你的ip地址做限制这个时候,你可以换代理重新抓。
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://google.com"); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //是否通过http代理来传输 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE); curl_setopt($ch, CURLOPT_PROXY, 125.21.23.6:8080); //url_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:password');如果要密码的话,加上这个 $result=curl_exec($ch); curl_close($ch); ?>
4.继续保持本站session的调用
在实现用户同步登录的情况下需要共享session,如果要继续保持本站的session,那么要把sessionid放到http请求中
<?php $session_str = session_name().'='.session_id().'; path=/; domain=.explame.com'; session_write_close(); //将数据写入文件并且结束session $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIE, $session_str); $ret = curl_exec($ch); curl_close($ch); ?>