Hàm fread

Hàm fread đọc dữ liệu từ một tệp đang mở. Tham số đầu tiên của hàm nhận một con trỏ tệp (tài nguyên), thu được thông qua fopen, và tham số thứ hai - số byte tối đa cần đọc. Hàm trả về dữ liệu đã đọc hoặc false trong trường hợp có lỗi.

Cú pháp

phpfread(resource $handle, int $length): string|false

Ví dụ

Hãy đọc 10 byte đầu tiên từ tệp:

php<?php
  $file = fopen('data.txt', 'r');
  $res = fread($file, 10);
  fclose($file);
  echo $res;
?>

Kết quả thực thi mã:

php'Some text '

Ví dụ

Hãy đọc toàn bộ tệp:

php<?php
  $file = fopen('data.txt', 'r');
  $res = fread($file, filesize('data.txt'));
  fclose($file);
  echo $res;
?>

Kết quả thực thi mã:

php'Complete file content'

Ví dụ

Hãy đọc tệp theo từng phần:

php<?php
  $file = fopen('data.txt', 'r');
  while (!feof($file)) {
    echo fread($file, 5) . "\n";
  }
  fclose($file);
?>

Kết quả thực thi mã:

php'First'
' part'
' of t'
'ext'

Xem thêm