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 ] )

Example

<?php
$file = fopen("test.txt","r");
echo fgets($file);
fclose($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.


Example

<?php
$file = fopen("test.txt","r");
echo fgetss($file);
fclose($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.


Example

<?php
$file = fopen("test.csv","r");
print_r(fgetcsv($file));
fclose($file);
?>





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




Read more articles


General Knowledge



Learn Popular Language