PHP读取网页文件内容的实现代码(fopen,curl等)

yipeiwu_com5年前PHP代码库
1.fopen实现代码:
复制代码 代码如下:

<?php
$handle = fopen ("http://www.example.com/", "rb");
$contents = "";
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>

复制代码 代码如下:

<?php
// 对 PHP 5 及更高版本
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>

2.curl实现代码:
复制代码 代码如下:

<?php
function _url($Date){
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, "$Date");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$contents = curl_exec($ch);
curl_close($ch);
return $contents;
}
$pageURL="http://www.baidu.com";
$contents=_url($pageURL);
?>

编码转换函数
复制代码 代码如下:

$html = file_get_contents("http://s.jb51.net");
$html = iconv( "Big5", "UTF-8//IGNORE" , $html); //转化编码方式为UTF8
print $html;
$htm = file("http://s.jb51.net");
$h = "";
foreach($htm as $value)
{
$h.= iconv( "GB2312", "utf-8//IGNORE" , $value);
}
print_r($h);

另一种打开网页的方法
复制代码 代码如下:

<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
/* Sends an http request to www.example.com
with additional headers shown above */
$fp = fopen('http://www.baidu.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>

相关文章

php+redis实现消息队列功能示例

本文实例讲述了php+redis实现消息队列功能。分享给大家供大家参考,具体如下: 个人理解在项目中使用消息队列一般是有如下几个原因: 把瞬间服务器的请求处理换成异步处理,缓解服务器的压...

Zend Guard使用指南及问题处理

Zend Guard是目前市面上最成熟的PHP源码加密产品了。 刚好需要对自己的产品进行加密,折腾了一晚上,终于搞定,将碰到的问题及解决方法记录下来,方便日后需要,也可以帮助其他人。 我...

PHP 递归效率分析

而且是差了3倍的效率。所以,PHP中的递归一定要小心的对待。 最近写了一个快速排序的算法,发现PHP中的递归效率不能一刀切,在各种不同的服务器中,可能会表现不一样。 复制代码 代码如下:...

php记录代码执行时间(实现代码)

复制代码 代码如下:$t1 = microtime(true);// ... 执行代码 ...$t2 = microtime(true);echo '耗时'.round($t2-$t1,...

php file_put_contents()功能函数(集成了fopen、fwrite、fclose)

命令:file_put_contents(); 命令解析:file_put_contents (PHP 5) file_put_contents -- 将一个字符串写入文件 说明: in...