PHP 檔案建立 寫入

2021-08-05 21:04:25 字數 1422 閱讀 2406

在本節中,我們將為您講解如何在伺服器上建立並寫入檔案。

fopen() 函式也用於建立檔案。也許有點混亂,但是在 php 中,建立檔案所用的函式與開啟檔案的相同。

如果您用 fopen() 開啟並不存在的檔案,此函式會建立檔案,假定檔案被開啟為寫入(w)或增加(a)。

下面的例子建立名為 「testfile.txt」 的新檔案。此檔案將被建立於 php **所在的相同目錄中:

$myfile = fopen("testfile.txt", "w")

如果您試圖執行這段**時發生錯誤,請檢查您是否有向硬碟寫入資訊的 php 檔案訪問許可權。

fwrite() 函式用於寫入檔案。

fwrite() 的第乙個引數包含要寫入的檔案的檔名,第二個引數是被寫的字串。

下面的例子把姓名寫入名為 「newfile.txt」 的新檔案中:

<?php

$myfile = fopen("newfile.txt", "w") or die("unable to open file!");

$txt = "bill gates\n";

fwrite($myfile, $txt);

$txt = "steve jobs\n";

fwrite($myfile, $txt);

fclose($myfile);

?>

請注意,我們向檔案 「newfile.txt」 寫了兩次。在每次我們向檔案寫入時,在我們傳送的字串 $txt 中,第一次包含 「bill gates」,第二次包含 「steve jobs」。在寫入完成後,我們使用 fclose() 函式來關閉檔案。

如果我們開啟 「newfile.txt」 檔案,它應該是這樣的:

bill gates

steve jobs

如果現在 「newfile.txt」 包含了一些資料,我們可以展示在寫入已有檔案時發生的的事情。所有已存在的資料會被擦除並以乙個新檔案開始。

在下面的例子中,我們開啟乙個已存在的檔案 「newfile.txt」,並向其中寫入了一些新資料:

<?php

$myfile = fopen("newfile.txt", "w") or die("unable to open file!");

$txt = "mickey mouse\n";

fwrite($myfile, $txt);

$txt = "minnie mouse\n";

fwrite($myfile, $txt);

fclose($myfile);

?>

如果現在我們開啟這個 「newfile.txt」 檔案,bill 和 steve 都已消失,只剩下我們剛寫入的資料:

mickey mouse

minnie mouse

PHP 檔案建立 寫入

php 檔案建立 寫入 fopen 函式也用於建立檔案。也許有點混亂,但是在 php 中,建立檔案所用的函式與開啟檔案的相同。如果您用 fopen 開啟並不存在的檔案,此函式會建立檔案,假定檔案被開啟為寫入 w 或增加 a php 寫入檔案 fwrite fwrite 函式用於寫入檔案。fwrite...

PHP 檔案寫入方法

1 fwrite fwrite 函式將內容寫入乙個開啟的檔案中。函式會在到達指定長度或讀到檔案末尾 eof 時 以先到者為準 停止執行。如果函式成功執行,則返回寫入的位元組數。如果失敗,則返回 false。語法 fwrite file,string,length 引數描述 file必需。規定要寫入的...

PHP寫入txt檔案

myfiletoread fopen txt readme.txt r or die unable to open file myfileread fread myfiletoread,20 myfiletowrite fopen txt writeme.txt a or die unable to...