PHP中獲取遠端檔案的三種方法

2021-08-20 12:52:11 字數 1749 閱讀 6506

<?php

$url = '';

$contents = file_get_contents($url);

//如果出現中文亂碼使用下面**

//$getcontent = iconv(「gb2312″, 「utf-8″,file_get_contents($url));

//echo $getcontent;

echo $contents;

?>

<?php

$url = 「」;

$ch = curl_init();

$timeout = 5;

curl_setopt($ch, curlopt_url, $url);

curl_setopt($ch, curlopt_returntransfer, 1);

curl_setopt($ch, curlopt_connecttimeout, $timeout);//在需要使用者檢測的網頁裡需要增加下面兩行

?>

php抓取外部資源函式fopen / file_get_contents / curl 的區別 

fopen / file_get_contents 每次請求都會重新做dns查詢,並不對dns資訊進行快取。 

但是curl會自動對dns資訊進行快取。對同一網域名稱下的網頁或者的請求只需要一次dns查詢。 

這大大減少了dns查詢的次數。 

所以curl的效能比fopen / file_get_contents 好很多。

1.使用

file_get_contents

和fopen

必須空間開啟

allow_url_fopen

。方法:編輯

php.ini,設定

allow_url_fopen = on

,allow_url_fopen

關閉時fopen

和file_get_contents

都不能開啟遠端檔案。

2.使用

curl

必須空間開啟

curl

。方法:

win下修改

php.ini

,將extension=php_curl.dll

前面的分號去掉,

而且需要拷貝

ssleay32.dll

和libeay32.dll

到c:\windows\system32

下;linux

下要安裝

curl

擴充套件。建議開啟

url時使用

file_get_contents()

方法,可優化開啟速度

PHP之讀取遠端檔案的三種方法

1.curl init exec url ch curl init timeout 5 curl setopt ch,curlopt url,url curl setopt ch,curlopt returntransfer,1 curl setopt ch,curlopt connecttimeo...

PHP獲取檔案字尾名的三種方法

php獲取檔案字尾名的三種方法。如下 function get file type filename php獲取檔案字尾名的幾種方法2 function get file type filename php獲取檔案字尾名的幾種方法3 function get file type filename 回...

php讀取檔案內容的三種方法

第一種讀取方式 如下 header content type text html charset utf 8 檔案路徑 file path text.txt 判斷是否有這個檔案 if file exists file path else else fclose fp 第二種讀取方式 如下 heade...