PHP differentiate between fgets, fgetss and fgetcsv

fgets() function

fgets() function reads one line at a time from a file. It reads until it encounters a new line character (\n) or EOF. The maximum length read is the length specified minus 1 byte.

You can use many different functions to read from files. The fgets() function, for example, is useful when you are dealing with a files that contain plain text that you want to deal with in chunks.

string fgets ( resource $handle [, int $length ] )


$file = fopen("test.txt","r");
echo fgets($file);

fgetss() function

An interesting variation on fgets() is fgetss(), which has the following syntax -

string fgetss(resource fp, int length, string [allowble_tags])

The function is similar to fgets() except that it strips out any PHP and HTML tags found in string. If you want to leave in any particular tags, you can add them in the allowable_tags string. You would use fgetss() for safety when reading a file written by someone else or containing user input.


$file = fopen("test.txt","r");
echo fgetss($file);

fgetcsv() function

The function fgetcsv() is another variation on fgets(). It has the following prototype.

array fgetcsv(resource fp, int length [, string  delimiter [, string enclosure]])

The function breaks up lines of files when you have used a delimiting character, such as the tab character or a comma. If you want to reconstruct the variable from the order separately rather than as a line of text, fgetcsv() allows you to do this simply.


$file = fopen("test.csv","r");

Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Insert image in database

Read more articles

General Knowledge

Learn Popular Language