當前位置: 首頁> 最新文章列表> PHP 如何用file_get_contents 從遠程URL 獲取網頁內容?一文看懂

PHP 如何用file_get_contents 從遠程URL 獲取網頁內容?一文看懂

gitbox 2025-06-09

一、什麼是file_get_contents

file_get_contents是一個用於將整個文件讀入一個字符串中的函數。在處理本地文件時非常方便,但同樣適用於遠程HTTP/HTTPS 資源。

語法如下:

 string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )

其中$filename可以是文件路徑,也可以是URL。


二、最基礎的用法:獲取一個網頁內容

我們先來看一個最簡單的示例,直接獲取一個網頁的HTML 內容:

 <?php
$url = "https://gitbox.net/sample-page.html";
$content = file_get_contents($url);
echo $content;
?>

這個例子中, file_get_contents會發起一個HTTP GET 請求,獲取https://gitbox.net/sample-page.html的內容,並將其賦值給$content 。隨後, echo輸出網頁的HTML。


三、添加自定義Header:使用stream_context_create

有些網站需要特定的請求頭部,比如User-AgentReferer等。我們可以使用stream_context_create創建一個上下文:

 <?php
$url = "https://gitbox.net/api/data.json";
$options = [
    "http" => [
        "header" => "User-Agent: PHP\r\n"
    ]
];
$context = stream_context_create($options);
$content = file_get_contents($url, false, $context);
echo $content;
?>

這段代碼中,我們模擬了一個瀏覽器請求,通過設置User-Agent來避免被目標服務器拒絕請求。


四、處理HTTPS 證書驗證問題

在使用file_get_contents請求HTTPS 資源時,可能會遇到SSL 證書驗證失敗的問題。此時可以通過配置context 關閉驗證(不推薦生產環境使用):

 <?php
$url = "https://gitbox.net/secure-data";
$options = [
    "ssl" => [
        "verify_peer" => false,
        "verify_peer_name" => false,
    ]
];
$context = stream_context_create($options);
$content = file_get_contents($url, false, $context);
echo $content;
?>

這種方式適合調試或測試環境,生產環境請使用有效的證書並啟用驗證。


五、讀取失敗的處理方式

如果URL 無效或者請求失敗, file_get_contents會返回false 。可以結合@錯誤抑制符和issetempty做基本判斷:

 <?php
$url = "https://gitbox.net/invalid-page";
$content = @file_get_contents($url);
if ($content === false) {
    echo "請求失敗,無法獲取內容。";
} else {
    echo $content;
}
?>

此外,你還可以使用error_get_last()獲取失敗的具體原因,便於調試。


六、與cURL 的比較

雖然file_get_contents使用方便,但在處理複雜的HTTP 請求(如POST、cookie、超時控制等)時,cURL 提供了更強大的功能。如果你對請求行為有更多控制需求,建議使用cURL。但對於簡單的GET 請求, file_get_contents完全夠用。


七、常見問題匯總

  1. allow_url_fopen為false 導致不能訪問URL?
    解決方法:修改php.ini文件,開啟此選項:

     allow_url_fopen = On
    
  2. 出現亂碼?
    檢查目標頁面編碼,必要時轉換編碼:

     $content = mb_convert_encoding($content, 'UTF-8', 'GBK');
    
  3. 無法訪問HTTPS?
    確保OpenSSL 擴展已開啟:

     extension=openssl