PHP读取网页文件内容的实现代码(fopen,curl等)
程序员文章站
2022-05-21 17:35:31
1.fopen实现代码:复制代码 代码如下:
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
$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 whois查询API制作方法
下一篇: IconFont的iOS使用