当前位置: 网学 > 编程文档 > PHP > 正文

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

来源:Http://myeducs.cn 联系QQ:点击这里给我发消息 作者: 用户投稿 来源: 网络 发布时间: 13/06/22

鉴于大家对PHP十分关注,我们编辑小组在此为大家搜集整理了“PHP读取网页文件内容的实现代码(fopen,curl等)”一文,供大家参考学习!

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);
?>

网学推荐

免费论文

原创论文

浏览:
设为首页 | 加入收藏 | 论文首页 | 论文专题 | 设计下载 | 网学软件 | 论文模板 | 论文资源 | 程序设计 | 关于网学 | 站内搜索 | 网学留言 | 友情链接 | 资料中心
版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved
湘ICP备09003080号