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
fread(resource $handle, int $length): string|false
Ví dụ
Hãy đọc 10 byte đầu tiên từ tệp:
<?php
$file = fopen('data.txt', 'r');
$res = fread($file, 10);
fclose($file);
echo $res;
?>
Kết quả thực thi mã:
'Some text '
Ví dụ
Hãy đọc toàn bộ tệp:
<?php
$file = fopen('data.txt', 'r');
$res = fread($file, filesize('data.txt'));
fclose($file);
echo $res;
?>
Kết quả thực thi mã:
'Complete file content'
Ví dụ
Hãy đọc tệp theo từng phần:
<?php
$file = fopen('data.txt', 'r');
while (!feof($file)) {
echo fread($file, 5) . "\n";
}
fclose($file);
?>
Kết quả thực thi mã:
'First'
' part'
' of t'
'ext'
Xem thêm
-
hàm
fwrite,
hàm ghi vào tệp -
hàm
fgets,
hàm đọc một dòng từ tệp -
hàm
file_get_contents,
hàm đọc toàn bộ tệp