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结合md5实现的加密解密方法

本文实例讲述了php结合md5实现的加密解密方法。分享给大家供大家参考,具体如下: 最近在整理代码发现了一个不错的东西,结合md5的加解密算法。网上关于php结合md5的加密,解密算法比...

PHP学习笔记之三 数据库基本操作

下面是在Linux上登录mysql,创建数据库和创建表的过程。 yin@yin-Ubuntu10:~$ mysql -u root -p Enter password: Welcome...

PHP使用debug_backtrace方法跟踪调试代码调用详解

本文实例讲述了PHP使用debug_backtrace方法跟踪调试代码调用。分享给大家供大家参考,具体如下: 在开发过程中,例如要修改别人开发的代码或调试出问题的代码,需要对代码流程一步...

PHP使用mongoclient简单操作mongodb数据库示例

本文实例讲述了PHP使用mongoclient简单操作mongodb数据库。分享给大家供大家参考,具体如下: 最好回到《mongodb shell基础命令【进阶篇】》,再来看这里的内容,...

php使用正则验证中文

php用preg_match来匹配并判断一个字符串中是否含有中文或者都是中文的方法如下: $str = 'php学习博客'; if(preg_match('/[\x7f-\xff]/...