How to read files in PHP

There are many options are available when it comes to file processing with PHP. Each option has its own importance. We will discuss some of the functions related to file processing, such as fopen, fclose, feof, file, file_get_contents etc. We will also discuss, when we should use which function, because it always depends on the goal of parsing the file.

Traditional fopen methods.

The fopen methods provides the procedural way to open a file in a given mode and then another function to read the file sequentially and finally close the file using function fclose.

$file_handle = fopen("myfile", "r"); while (!feof($file_handle)) { $line = fgets($file_handle); echo $line; } fclose($file_handle);

In the given example, first we are opening a file using fopen and getting it reference to $file_handle. Now, we accessing it till end of file, using feof and printing each line. After that, we are closing the file with fclose function.

fopen : It creates a connection to the given file. The file can be local or remote. For example,

$file_handle = fopen(“http://yourdomain.com”, “r”);

feof : It checks whether you have read the end of the file or not and returns True or False. It will also returns False, if the socket is closed and you have no longer data available to read.

fclose : It closes the connection with the file or URL, just opposite to the fopen function.

fgets : It grabs a single line of data from your file and returns it as a string.

fread : It comes handy when you want to bypass line by line reading. It grabs a chunk of data or given bytes with the maximum size of 8 KB.

fgetss : It acts same as fgets only that it strips the HTML and PHP tags and gives only the texts.

If we want to grab the whole file as once, we can use the following functions.

file_get_contents : It grabs all the files at once and stores it in a string. It also can be triggered with an offset and maxlen to read a specific chunk of a file.

readfile : It reads the entire content of a file and writes it to a default output buffer.

tip: It throws an error if it fails. to escape that use @readfile.

file : If you want to read a file to get each line of your file as an entry of an array. You can use file method. it will return an array of each line.

There are some specific methods to read some specific type of files. For example,

parse_ini_file : It parses the ini files. If you want to parse a ini file section-wise, you can set the second argument to true.

fgetcsv : reads a CSV file and returns an array of the given file.

Conclusion:

If you’ve a large amounts of data to process, fscanf will probably be more valuable and efficient. In contrast, if

you’re simply echoing a large amount of text with little modification, file, file_get_contents, or readfile will be more handy.

Leave a Reply