The fgetc Function
The fgetc
function reads and returns one character from a file.
The function takes a file pointer as a parameter,
returns a string with one character or false
if the end of the file has been reached.
Syntax
fgetc(resource $handle): string|false
Example
Read a file character by character and output each character:
<?php
$file = fopen('test.txt', 'r');
if ($file) {
while (($char = fgetc($file)) !== false) {
echo $char;
}
fclose($file);
}
?>
Example
Read only the first character from the file:
<?php
$file = fopen('test.txt', 'r');
if ($file) {
$char = fgetc($file);
echo $char;
fclose($file);
}
?>
Example
Handling the case when the end of the file is reached:
<?php
$file = fopen('empty.txt', 'r');
if ($file) {
$res = fgetc($file);
var_dump($res);
fclose($file);
}
?>