PHP中獲取遠程文件的三種方法

1.file_get_contents

<?phpphp

$url = 'http://www.xxx.com/';
$contents = file_get_contents($url);
//若是出現中文亂碼使用下面代碼
//$getcontent = iconv(「gb2312″, 「utf-8″,file_get_contents($url));
//echo $getcontent;
echo $contents;
?>

2.curl

<?phpcurl

$url = 「http://www.xxx.com/」;
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);//在須要用戶檢測的網頁裏須要增長下面兩行
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.」:」.US_PWD);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;

?>優化

3.fopen->fread->fclose

<?phpurl

$handle = fopen (「http://www.xxx.com/」, 「rb」);
$contents = 「」;
do {
$data = fread($handle, 8192);
if (strlen($data) == 0)
{break;}
$contents .= $data;
} while(true);
fclose ($handle);
echo $contents;

?>spa

 

file_get_contents、fopen、curl區別分析:

1.使用file_get_contents和fopen必須空間開啓allow_url_fopen。utf-8

方法:編輯php.ini,設置 allow_url_fopen = On,allow_url_fopen關閉時fopen和file_get_contents都不能打開遠程文件。ssl

2.使用curl必須空間開啓curl。get

方法:WIN下修改php.ini,將extension=php_curl.dll前面的分號去掉,並且須要拷貝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;it

Linux下要安裝curl擴展。io

建議打開URL時使用file_get_contents()方法,可優化打開速度

相關文章
相關標籤/搜索