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

相关文章

攻克CakePHP系列二 表单数据显示

攻克CakePHP系列二 表单数据显示

首先建立数据库cake_ext,并执行如下sql文: CREATE TABLE `companies` (   `id` ...

PHP与以太坊交互详解

自去年以来,我们正在开发区块链(Blockchain)业务。最近使用过Ethereum并使用PHP,所以我想我们应该聊聊这个话题。 这里有个前提: 1.理解区块链 2.对编程语言有了解...

详谈symfony window下的安装 安装时候出现的问题以及解决方法

1. cmd进入DOS  , cd 到 php.exe 的目录下 2. php -r "readfile('http://symfony.com/installer');" &...

php自定义中文字符串截取函数substr_for_gb2312及substr_for_utf8示例

本文实例讲述了php自定义中文字符串截取函数substr_for_gb2312及substr_for_utf8用法。分享给大家供大家参考,具体如下: /* *gb2312中文字符串截...

PHP获取当前相对于域名目录的方法

本文实例讲述了PHP获取当前相对于域名目录的方法。分享给大家供大家参考。具体如下: http://127.0.0.1/dev/classd/index.php/download 比如这个...