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.cc");
$html = iconv( "Big5","UTF-8//IGnorE",$html); //转化编码方式为UTF8
print $html;
$htm = file("http://s.jb51.cc");
$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);
?>

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...