update: 751view
【PHP】テキストファイルの読み込みと書き込み方

テキストファイルの読み込み
- $str = '';
- // 読み込みたいファイルのパスを指定
- $filepath = 'test_data.txt';
-
- // ファイルを開く
- $fp = fopen($filepath, 'r');
-
- while (!feof($fp)) {
- $txt = fgets($fp);
- //変数strに格納
- $str .= $txt;
- }
- // ファイルを閉じる
- fclose($fp);
- echo $str;
-
ファイルを操作するモード
- r
- 読み込みのみ
- r+
- 読み込みと書き込み
- w
- 書き込みのみ
- w+
- 読み込みと書き込み
- a
- 末尾に追加で上書き
- a+
- 読み込みと末尾に書き込み
テキストファイルの書き込み
- $str = 'aaaaaa';
- // 書き込みたいファイルのパスを指定
- $filepath = 'test_data.txt';
-
- // ファイルを開く
- $fp = fopen($filepath, 'a');
-
- @fwrite($a, $str."\n");
- fclose($a);
-