関数 fread
関数 fread は、開いたファイルからデータを読み取ります。第一引数は、fopen を通して取得したファイルポインタ(リソース)を受け取り、第二引数は読み取る最大バイト数です。この関数は読み取ったデータ、またはエラーの場合は false を返します。
構文
fread(resource $handle, int $length): string|false
例
ファイルの最初の 10 バイトを読み取ります:
<?php
$file = fopen('data.txt', 'r');
$res = fread($file, 10);
fclose($file);
echo $res;
?>
コードの実行結果:
'Some text '
例
ファイル全体を読み取ります:
<?php
$file = fopen('data.txt', 'r');
$res = fread($file, filesize('data.txt'));
fclose($file);
echo $res;
?>
コードの実行結果:
'Complete file content'
例
ファイルを部分ごとに読み取ります:
<?php
$file = fopen('data.txt', 'r');
while (!feof($file)) {
echo fread($file, 5) . "\n";
}
fclose($file);
?>
コードの実行結果:
'First'
' part'
' of t'
'ext'
関連項目
-
関数
fwrite,
ファイルへの書き込みを行います -
関数
fgets,
ファイルから一行を読み取ります -
関数
file_get_contents,
ファイル全体を読み取ります