PHP fgetc(): Get a Single Character from a File

The PHP fgetc() function fetches and returns a single character from a file. For example:

<?php
   $fp = fopen("codescracker.txt", "r");
   echo fgetc($fp);
   fclose($fp);
?>

The output produced by the above PHP example on the fgetc() function is:

php fgetc function

That is, the output is H, which is the first character of the file codescracker.txt. Here is a snapshot of the opened file codescracker.txt, available in the current directory:

php fgetc example

Note: The fopen() function opens a file.

Note: The fclose() function closes a file.

You can use feof() to continue fetching until the end of the file and the fgetc() function to read all the content of the file in a character-by-character manner. Here is an example:

<?php
   $fp = fopen("codescracker.txt", "r");
   if($fp)
   {
      while(!feof($fp))
      {
         $character = fgetc($fp);
         if($character == "\n")
            echo "<br>";
         else
            echo $character;
      }
      fclose($fp);
   }
   else
      echo "<p>Unable to open the file!</p>";
?>

Now the output should be:

php fgetc get character by character

Note: The feof() function checks whether the file pointer has been reached at the end of the file.

Recommendation: Since this function fetches data in a character-by-character manner, it makes your application slower for large files. But still, if you need to fetch data character-by-character, you can use the fgets() function to read one line, then fetch that line character-by-character, then do the same for the second line, and so on.

PHP fgetc() Syntax

The syntax of the fgetc() function in PHP is:

fgetc(filePointer)

Advantages of the fgetc() function in PHP

Disadvantages of the fgetc() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!