0
0

More than 3 years have passed since last update.

PHPを使ったファイル操作の基本

Last updated at Posted at 2020-05-12

簡易まとめ

使用した関数

sample
//$file_pathにあるファイルを開く
$open_file = fopen($file_path, 'r');
//ポインターの場所を取得
ftell($open_file)
//ポインターある位置の文字を取得する
fgetc($open_file)
//ポインターがある位置からその行の最後までを取得する。また、ポインターが取得したバイト数分移動する
fgets($open_file)
//ポインターの場所をファイルの先頭から指定したバイト数分移動した位置に変更する
fseek($open_file, bytes)

example.txt
1line
2line
3line
4line
5line
example.php
<?php
$file_path = "./example.txt"; //pathは自分の環境似合わせてね!
$open_file = fopen($file_path, 'r');
echo("何もしていない時のポインター位置: ".ftell($open_file)."\n");
echo(fgets($open_file));
echo("fgets()を一回実行した後のポインター位置: ".ftell($open_file)."\n");
echo(fgets($open_file));
fseek($open_file, 6);
echo("fseek($open_file, 6)を実行した後のポインター位置: ".ftell($open_file)."\n");
echo(fgets($open_file)."\n");

//おまけ
fseek($open_file, 1);
echo(fgetc($open_file)."\n");
echo(fgets($open_file));
echo(fgets($open_file));
echo(fgets($open_file));
echo(fgets($open_file));
echo(fgets($open_file));
?>

terminalでphp ./example.phpを実行する

結果
何もしていない時のポインター位置: 0
1line
fgets()を一回実行した後のポインター位置: 6
2line
fseek(Resource id #5, 6)を実行した後のポインター位置: 6
2line

l
ine
2line
3line
4line
5line
0
0
2

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