The following code shows an Example of fgetc() Function in PHP.

When we need to read a single character of a file, we can use the fgetc() function. Also, we can read the whole contents of the file in a loop. Furthermore, we can also read an arbitrary character of the file by moving the file pointer at a specified character using the fseek() function.

Suppose we have the following text file that we read using the fgetc() function.

phpfiles.txt
phpfiles.txt

Initially, the file pointer points at the beginning of the file. So, the first call to this function returns the first character of the file. After that, the file pointer proceeds to the next character. Also, we can use the fseek() function that moves the file pointer to the specified character.

In order to read the whole content of the file, first, we call the fseek() function again and place the file pointer at the start of the file. When the end of the file is reached, the feof() function returns true. So, in the while loop, we check this condition and print each character of the file one by one.

<?php
  $myfile=fopen('phpfiles.txt', 'r');
  //reading the first character
  echo 'First chracter in the file...<br>';
  echo fgetc($myfile);
  fseek($myfile, 100);
  echo '<br>100th chracter in the file...<br>';
  echo fgetc($myfile);
  //Reading the whole content of the file

  echo '<br>Reading the complete file...<br>';
  fseek($myfile, 0);
  while(!feof($myfile))
  {
     echo fgetc($myfile);

  }
  fclose($myfile);
?>

Output

Example of fgetc() Function in PHP -Reading a File Character By Character
Example of fgetc() Function in PHP -Reading a File Character By Character

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

programmingempire

princites.com