curl 简单使用

很多同学喜欢用file_get_contents()函数来采集一个页面内容,

<?php
        $str = file_get_contents('http://bbs.lambrother.net');
        //其实还有一些 
        $str = file("http://bbs.lampbrother.net");
        $str = readfile("http://bbs.lampbrother.net");
?>

这样其实没办法有效的进行错误处理,更重要的没法完成一些高难度任务:
如处理cookies, 验证, 表单提交, 文件上传等等。

cURL 四板斧

<?php
//1. 初始化, 创建一个新curl资源
$ch = curl_init();
//2. 设置url和相应的选项 最重要的一步,其他都是套路
curl_setopt($ch, CURLOPT_URL, "http://www.lampbrother.net/");
curl_setopt($ch, CURLOPT_HEADER, 0);
//3.抓取url 并把它传递给浏览器
curl_exec($ch);
//4.关闭curl 资源,并且释放系统资源
curl_close($ch);
?>

功能强大,效率比file_get_contents 高出四倍以上, 稳定性也100分

get post 模拟
get:

  //初始化
  $ch = curl_init();
  //设置选项,包括URL
  curl_setopt($ch, CURLOPT_URL, "http://www.jb51.net");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  //执行并获取HTML文档内容
  $output = curl_exec($ch);
  //释放curl句柄
  curl_close($ch);
  //打印获得的数据
  print_r($output);

post:

 $url = "http://localhost/web_services.php";
  $post_data = array ("username" => "bob","key" => "12345");
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  // post数据
  curl_setopt($ch, CURLOPT_POST, 1);
  // post的变量
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  $output = curl_exec($ch);
  curl_close($ch);
  //打印获得的数据
  print_r($output);

 以上方式获取到的数据是json格式的,使用json_decode函数解释成数组。

  $output_array = json_decode($output,true);

  如果使用json_decode($output)解析的话,将会得到object类型的数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值