Giới thiệu
Hàm fprintf() ghi chuỗi định dạng vào stream (file handle, socket...). Giống printf() nhưng xuất ra stream thay vì stdout.
Cú pháp
fprintf(resource $stream, string $format, mixed ...$values): int
Tham số
- stream - Resource stream (từ
fopen(),STDOUT,STDERR...). - format - Chuỗi định dạng (placeholder giống
sprintf()/printf()). - values - Các giá trị chèn vào placeholder.
Giá trị trả về
Trả về độ dài chuỗi đã ghi (số byte).
Ví dụ
<?php
$input = 123;
$file = fopen("sample.txt", "w"); // Phải mở chế độ "w" để ghi
fprintf($file, "%f", $input);
fclose($file);
?>
Kết quả (nội dung sample.txt):
123.000000
Lưu ý: Code gốc mở file chế độ "r" (read) sẽ lỗi khi ghi. Đã sửa thành "w".