php发送http请求,获取网页内容方法

PHP发送http请求,获取网页内容方法:cURL、file_get_contents()、fopen()
区别:
1. 相较于file_get_contents()、fopen(),cURL支持更多功能

cURL支持更多协议,目前支持http、https、ftp、gopher、telnet、dict、file、Idap协议,同时也支持HTTPS认证、HTTP POST、HTTP PUT、FTP上传(这个也能通过PHP的FTP扩展完成)、HTTP基于表单的上传、代理、cookies和用户名+密码的认证。PHP中使用cURL实现get和post请求的方法。

2. 相较于file_get_contents()、fopen(),cURL性能更高

cURL性能更高的原因在于:file_get_contents()、fopen()每次请求都会重新做DNS查询,并不会对DNS信息进行缓存;cURL会自动对DNS信息进行缓存,同一域名下的网页或图片的请求只需要一次DNS查询,大大减少对DNS查询的次数。

3. get请求时,相较于cURL,file_get_contents()、fopen()设置更简单,代码量少,file_get_contents()代码量最少

file_get_contents()、fopen()默认使用get请求方式,如果需要使用post方式,可以使用stream_context_create()进行设置。

4. file_get_contents()、fopen()常用于读取文件内容

file_get_contents()把整个文件读入到一个字符串中,把文件内容读入到一个字符串中的首选方法。fopen()是打开文件,可设置不同的打开规则,然后对文件进行读取等操作

一般情况下,常使用cURL发送http请求,对于性能要求不高,简单的get请求,使用file_get_contents()、fopen()就更为简洁、代码量少。

一、cURL使用示例
<?php
//请求参数
$params = array(
    'aa' => '123',
    'bb' => '456'
);

//初始化cURL
$ch = curl_init(); 

//设置相应的会话选项 
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");   //设置curl地址
curl_setopt($ch, CURLOPT_POST, 1);    //设置curl发送方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);   //设置curl发送数据
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   //设置提交成功后,把数据返回为字符串

//执行发送
$output = curl_exec($ch);

//关闭cURL资源,并且释放系统资源 
curl_close($ch); 
echo $output;
?>
二、file_get_contents()使用示例

get请求:

<?php
$fh = file_get_contents('http://www.example.com/'); 
echo $fh;
?>

post请求,需用stream_context_create()进行设置:

<?php
//请求参数
$params = array(
    'aa' => '123’,
    'bb' => '456'
);

//将参数数组拼接成字符串
$params = http_build_query($params);

$options = array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-type:application/x-www-form-urlencode',
        'content' => $params,
        'timeout' => 60 //超时时间(单位:s)
    )
);
$url = 'http://www.example.com/';
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
?>
三、fopen()使用示例
<?php 
$fh = fopen('http://www.example.com/', 'r');
if($fh) { 
    while(!feof($fh)) { 
        echo fgets($fh); 
    } 
} 
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值