0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP fopenでファイルを開いて使用する

Last updated at Posted at 2021-03-29

fopenの例

読み込み・追加の処理

txt.txt

abcdefg
one,two,three
12345
アイウエオ

fopen.php

<?php 
//$変数名(ファイルポインタ) = fopen (“開きたいファイル名”, “オープンモード”);

// 読み込みモードでファイルを開く
$fp = fopen("txt.txt", "r");

// ファイルを1行ずつ取得する
while ($line = fgets($fp)) {
  echo "$line";
}

// ファイルを閉じる
fclose($fp);

//結果
/*
abcdefg
one,two,three
12345
アイウエオ
*/

//追加の記述(末尾に追加される)
$fa = fopen('txt.txt','a');
fwrite($fa,"\n".'5行目に追加');
fclose($fa);

$fr = fopen('txt.txt','r');
while($line = fgets($fr)){
    echo $line;
}
/*
//結果
/*
abcdefg
one,two,three
12345
アイウエオ
5行目に追加
*/

上書きの処理

さらにこの記述の後に以下のコードを実行すると上書きされる。

$fw = fopen('txt.txt','w');
fwrite($fw,'上書きして1行になります');
fclose($fw);

$fr = fopen('txt.txt','r');
while($line = fgets($fr)){
    echo $line;
}
fclose($fr);
//結果
//上書きして1行になります

fopen()の第二引数について

以下の用途で指定する
参考:phpドキュメント
スクリーンショット 2021-03-29 15.33.16.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?