nobee

update: 751view

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

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

テキストファイルの読み込み

  1. $str = '';
  2. // 読み込みたいファイルのパスを指定
  3. $filepath = 'test_data.txt';
  4. // ファイルを開く
  5. $fp = fopen($filepath, 'r');
  6. while (!feof($fp)) {
  7. $txt = fgets($fp);
  8.  //変数strに格納
  9. $str .= $txt;
  10. }
  11. // ファイルを閉じる
  12. fclose($fp);
  13. echo $str;

ファイルを操作するモード

r
読み込みのみ
r+
読み込みと書き込み
w
書き込みのみ
w+
読み込みと書き込み
a
末尾に追加で上書き
a+
読み込みと末尾に書き込み

テキストファイルの書き込み

  1. $str = 'aaaaaa';
  2. // 書き込みたいファイルのパスを指定
  3. $filepath = 'test_data.txt';
  4. // ファイルを開く
  5. $fp = fopen($filepath, 'a');
  6. @fwrite($a, $str."\n");
  7. fclose($a);

share

人気記事