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配置文件php.ini的路径的方法

图解找出PHP配置文件php.ini的路径的方法

近来,有不博友问php.ini存在哪个目录下?或者修改php.ini以后为何没有生效?基于以上两个问题,我觉得有必要教一下刚接触PHP的博友们如何找到PHP调用php.ini的路径目录。...

PHP实现获取文件后缀名的几种常用方法

本文实例讲述了PHP实现获取文件后缀名的几种常用方法。分享给大家供大家参考。具体如下: 方法1: function get_file_type($filename){ $type...

php基于curl重写file_get_contents函数实例

本文实例讲述了php基于curl重写file_get_contents函数。分享给大家供大家参考,具体如下: file_get_contents在连接不上的时候会提示Connection...

PHP获取文件扩展名的方法实例总结

本文实例总结了PHP获取文件扩展名的方法。分享给大家供大家参考,具体如下: 在PHP面试中或者考试中会有很大几率碰到写出五种获取文件扩展名的方法,下面是我自己总结的一些方法 $fil...

PHP函数checkdnsrr用法详解(Windows平台用法)

本文实例讲述了PHP函数checkdnsrr用法。分享给大家供大家参考,具体如下: 在php.net上是这样说的: (PHP 4, PHP 5) checkdnsrr — Check D...