PHP讀取檔案並可支援遠程檔案的代碼分享

來源:互聯網
上載者:User

php讀取檔案

案例一 複製代碼 代碼如下:<?php
$file = 'jb51.net.php';
//本案例不支援遠程
$fso = fopen($file, 'r');
echo $data = fread($fso, filesize($file));
fclose($fso);
?>

fopen() 將 file 指定的名字資源綁定到一個流上.
filesize 返迴文件大小的位元組數,如果出錯返回 FALSE.
注: 因為 PHP 的整數類型是有符號的,並且大多數平台使用 32 位整數,filesize() 函數在碰到大於 2GB 的檔案時可能會返回非預期的結果.對於 2GB 到 4GB 之間的檔案通常可以使用 sprintf("%u", filesize($file)) 來克服此問題.
fread() 從檔案指標 handle 讀取最多 length 個位元組. 該函數在讀取完 length 個位元組數,或到達 EOF 的時候,或(對於網路流)當一個包可用時就會停止讀取檔案,視乎先碰到哪種情況.
說明:低版本用法!建議php5用file_get_contents

案例二 複製代碼 代碼如下:<?php
$file = 'jb51.net.php';
//支援遠程
$file = 'http://www.jb51.net';//
echo $data = implode('', file($file));
?>

file -- 把整個檔案讀入一個數組中
說明
讀取二進位的檔案

案例三 複製代碼 代碼如下:<?php
$file = 'http://www.jb51.net';
echo file_get_contents($file);
?>

file_get_contents -- 將整個檔案讀入一個字串
說明
string file_get_contents ( string filename [, int use_include_path [, resource context]])
和 file() 一樣,只除了 file_get_contents() 將檔案返回為一個字串.
file_get_contents() 函數是用來將檔案的內容讀入到一個字串中的首選方法.如果作業系統支援還會使用記憶體映射技術來增強效能.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.