要想使用CURL ,首先要开启CURL扩展:
//取消下面的注释 extension=php_curl.dll
如何使用:
// 1. 初始化
$ch = curl_init();
// 2. 设置选项,包括URL
curl_setopt($ch, CURLOPT_URL, "http://www.doucube.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// 3. 执行并获取HTML文档内容
$output = curl_exec($ch);
// 4. 释放curl句柄
curl_close($ch);
简单的网页爬虫:
<?php
$ch=curl_init("http://www.baidu.com");
curl_exec($ch);
curl_close($ch);
?>
抓取网页并修改内容
<?php
$ch=curl_init();
curl_setopt($ch,curlopt_url,"http://www.baidu.com"); //设置URL
curl_setopt($ch,,curlopt_returntransfer,true); //不直接打印出来
$output=curl_exec($ch);
curl_close($ch);
echo str_replace("百度",“高富帅”,$output);
?>
webservise post 获取天气信息
<?php
$data="cityname=西安";
$ch=curl_init();
curl_setopt($ch,curlopt_url,"此处放置url");
curl_setopt($ch,curlopt_returntransfer,true);
curl_setopt($ch,curlopt_post,1);
curl_setopt($ch,curlopt_postfields,$data);
curl_setopt($ch,curlopt_httpheader,array("application/x-www-form-urlencode;charset=utf-8","content-length:".strlen($data)));
$output=curl_exec($ch);
if(!curl_errno($ch)){
echo $output;
}else{
///
}
curl_close($ch);
?>
登录网站并进行相关操作:
<?php
$data="username=yangzie@126.com&password=123456&remeber=1";
$ch=curl_init();
curl_setopt($ch,curlopt_url,"http://www.baisu.com/user/login");
curl_setopt($ch,curlopt_returntransfer,true);
//cookie相关设置,需要在所有会话开始之前设置
date_default_timezone_set("PRC");//使用cookie必须先设置时区
curl_setopt($ch,curlopt_cookiesession,true);
curl_setopt($ch,curlopt_cookiefile,"cookiefile");
curl_setopt($ch,curlopt_cookiejar,"cookiefile");
curl_setopt($ch,curlopt_cookie,session_name().'='.seession_id());
curl_setopt($ch,cutlopt_header,0);
curl_setopt($ch,curlopt_followlocation,1);//让URL支持页面链接跳转
curt_setopt($ch,curlopt_post,1);
curl_setopt($ch,curlopt_postfields,$data);
curl_setopt($ch,curlopt_httpheader,array("application/x-www-form-urlencode;charset=utf-8","content-length:".strlen($data)));
curl_exec($ch);
curl_setopt($ch,curlopt_url,"http://www.bai.com");//登录成功后重新设置要访问的url
curt_setopt($ch,curlopt_post,0);
curl_setopt($ch,curlopt_httpheader,array(“content-type:text/xml”);
$output=curl_exec($ch);
curl_close($ch);
echo $output;
?>
从FTP下载文件
<?php
$ch=curl_init();
curl_setopt($ch,curlopt_url,此处放置完整的url);
curl_setopt($ch,curlopt_header,0);
curl_setopt($ch,curlopt_returntransfer,1);
curl_setopt($ch,curlopt_timeout,300);
curl_setopt($ch,curlopt_userpwd,"yangzie:123456");
$outfile=fopen("fff.txt"."wb");
curl_setopt($ch,curlopt_file,$outfile);
$rtn=curl_exec($ch);
fcloase($outfile);
//错误判断