fopen 開啟檔案或URL
完整說明:http://php.net/manual/zh/function.fopen.php
|
模式 |
名稱 |
功用 |
|
r |
Read |
開啟檔案,以供讀取,從檔案開頭開始 |
|
r+ |
Read |
開啟檔案,以供讀取及寫入,從檔案開頭開始 |
|
w |
Write |
開啟檔案,並寫入(覆寫) |
|
w+ |
Write |
開啟檔案,以供讀取及寫入(覆寫) |
|
x |
Cautious write |
開啟檔案並寫入,假如檔案已存在,不會開啟開檔,fopen()會回傳false |
|
x+ |
Cautious write |
開啟檔案,供讀取及寫入,假如檔案已存在,不會開啟開檔,fopen()會回傳false |
|
a |
Append |
開啟檔案,以供新增內容,接續在目前已有的內容之後開始寫入,假如檔案不存在,會建立一個新檔 |
|
a+ |
Append |
開啟檔案,以供新增及讀取內容,接續在目前已有的內容之後開始寫入,假如檔案不存在,會建立一個新檔 |
寫入檔案
<?php
str = "Hello World";
file = fopen("test.xml","a+"); //開啟檔案
fwrite(file,str);
fclose(file);
?>
讀取檔案
<?php
filename = "test";
str = "";
//判斷是否有該檔案
if(file_exists(filename)){
file = fopen(filename, "r");
if(file != NULL){
//當檔案未執行到最後一筆,迴圈繼續執行(fgets一次抓一行)
while (!feof(file)) {
str .= fgets(file);
}
fclose(file);
}
}
echo str;
?>
