程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> PHP讀取網頁文件內容的實現代碼(fopen,curl等)

PHP讀取網頁文件內容的實現代碼(fopen,curl等)

編輯: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);
?>
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved