file_get_contents()
<?php
$url = 'http://news.ifeng.com/';
$content = file_get_contents($url);
//如果出现中文乱码使用下面代码
$content = iconv('gb2312', 'utf-8', $content);
echo $content;
?>
curl
<?php
$url = 'http://news.ifeng.com/';
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
//用户检测的时候加入以下代码
// curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
// curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;
?>
- CURLOPT_RETURNTRANSFER 将curl_exec()获取的信息以文件流的形式返回,而不是直接输出。
- CURLOPT_HTTPAUTH 使用的HTTP验证方法 CURLOPT_USERPWD
- 传递一个连接中需要的用户名和密码,格式为:”[username]:[password]”。
fopen()函数
<?php
$handle = fopen ("http://news.ifeng.com/", "rb");
$contents = "";
do
{
$data = fread($handle, 1024);
if (strlen($data) == 0)
{
break;
}
$contents .= $data;
}
while(true);
fclose ($handle);
echo $contents;
?>
string fread ( resource
handle,int
length )
读取文件,可安全用于二进制文件
从文件指针 handle 读取最多length个字节
bool fclose ( resource $handle )
关闭一个已打开的文件指针
注意:
- 使用file_get_contents和fopen必须空间开启allow_url_fopen。
编辑php.ini,设置allow_url_fopen =
On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。 - 使用curl必须空间开启curl。
修改php.ini,将extension=php_curl.dll前面的分号去掉。
Linux下要安装curl扩展。