檔
你經常有保存或讀取在web開發中的資源做一個簡單的方法是從文件中讀取和寫入。
閱讀文件
我們將介紹使用
file_get_contents函數讀取一個文件的最簡單方法。
Simply give it the relative path of the file to read / /簡單地給它的文件的相對路徑讀取
contents = file_get_contents ( ' text . txt ' ) ; $內容= file_get_contents(“文本txt');
$ contents ; 迴聲 $的內容;
文件讀取的text.txt文件,並輸出到一個字符串。 這是最簡單的方法來讀取一個文件,你也可以限制你讀到這樣的金額
contents = file_get_contents ( ' text . txt ' , false , null , 0 , 1024 ) ;內容= file_get_contents(“文本TXT。”,FALSE,NULL,0,1024);
這讀取的前1024個字節或第一千字節。 您還可以使用
file_get_contents函數來讀取網頁所以:
Simply give it the url of the web page to read / /簡單地給它讀取網頁的URL
contents = file_get_contents ( ' http : // www . google . com ' ) ; $內容= file_get_contents('。HTTP:/ / WWW谷歌COM“);
會讀谷歌的主網頁!
寫入文件
寫入文件的最簡單方法是使用
file_put_contents功能。
Simply give it the file to write to and the data / /簡單地給它的文件寫入數據
data = ' hi there ' ; 元數據=“喜有”;
' text . txt ' , $ data ) ; file_put_contents(TXT文本元數據);
如果有錯誤或如果它是全成,所以我們可以進一步提高,有些像邏輯代碼寫的字節數返回false:
Simply give it the file to write to and the data / /簡單地給它的文件寫入數據
data = ' hi there ' ; 元數據=“喜有”;
file_put_contents ( ' text . txt ' , $ data ) ) 如果(!file_put_contents(“文本。txt'的數據$))
{
" There was an error writing your data to the text . txt file " ; 迴聲 “是一個錯誤數據寫入TXT文本文件”。;
}
這個功能實際上是將創建一個不存在的文件,默認情況下,以及覆蓋現有文件。 因此,它可能是一個好主意,只讓通過設置文件的附加標誌的文件追加。
Simply give it the file to write to and the data / /簡單地給它的文件寫入數據
data = ' hi there ' ; 元數據=“喜有”;
file_put_contents ( ' text . txt ' , $ data , FILE_APPEND ) ) 如果(file_put_contents(“文本。txt'的 元數據,FILE_APPEND))
{
" There was an error writing your data to the text . txt file " ; 迴聲 “是一個錯誤數據寫入TXT文本文件”。;
}
良好做法
一般處理文件時,它很高興地看到,如果該文件,然後用它做的東西存在,這使得你的代碼更可靠。 要做到這
file_exists函數可以使用。
Simply give it the file name to check that exists / /簡單地給它的文件名 檢查存在
file_exists ( ' text . txt ' ) ) 如果(file_exists(“文本。txt'的 ))
{
" Your file doesn ' t exist ! " ; 呼應 “您的文件不存在!”;
返回;
}
/ *
Rest of the file accessing code . *其他文件的存取代碼。
* /
已提供任何意見。
書面由多米尼克·斯金納
最後更新:2011年10月25日十六點00分38秒