php取得遠端檔案方法有哪些

青灯夜游
發布: 2023-03-12 20:52:01
原創
3321 人瀏覽過

方法:1、使用「file_get_contents($url)」語句取得;2、開啟curl,使用curl_init()、curl_setopt()等函數取得;3、使用「fread(fopen("$url" ,"rb"),8192)」語句取得。

php取得遠端檔案方法有哪些

本教學操作環境:windows7系統、PHP7.1版,DELL G3電腦

1.file_get_contents

$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

#
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

$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;
登入後複製

file_get_contents、fopen、curl區別分析:

1、使用#file_get_contents#和fopen必須空間開啟allow_url_fopen

方法:編輯php.ini,設定 allow_url_fopen = Onallow_url_fopen關閉時fopenfile_get_contents#都不能打開遠端文件。

2、使用curl必須空間開啟curl

方法:WIN下修改php.ini,將extension=php_curl.dll前面的分號去掉,#而且需要拷貝ssleay32.dll libeay32.dllC:\WINDOWS\system32下;

Linux#下要安裝curl擴充功能。

建議開啟URL時使用file_get_contents()方法,可最佳化開啟速度

推薦學習:《PHP影片教學

以上是php取得遠端檔案方法有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
php
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!