Home >Backend Development >PHP Tutorial >PHP file read into array
For the convenience of processing, I used fgets() to define a function that can read the file content into an array. The i-th line of the file corresponds to the i-th element of the array (index is i-1). The following is the source code
function file2array($filename){ // read a file into an array // each element of the array is a line of file // also use explode("\r\n", file_get_contents($filename)) $f = fopen($filename,"r") or die("Unable to open the file '" . $filename . "'!"); $array=array(); while(!feof($f)) { array_push($array, str_replace("\r\n","",fgets($f))); } fclose($f); return $array; }
str_replace("\r\n","",fgets($f))is that fgets will also read in newline characters. You can use count() to check the length of the string. You will find that each line read is the corresponding line in the file. There are two more characters. The equivalent procedure is
explode("\r\n", file_get_contents($filename))
Use the following code to restore (write) an array to a file.
function array2file($array, $filename, $mode="w"){ // write an array (1-dim) in a file $f = fopen($filename, $mode) or die("Unable to open the file '" . $filename . "'!"); // $f = savefopen($filename, $mode); if (! empty($array)) { $first=array_shift($array); fwrite($f, $first); foreach ($array as $line) { fwrite($f, "\r\n" . $line); } } fclose($f); }
I also wrote some simple and useful file operation functions for everyone to use.
function file2str($filename){ // read a file into a string $f = fopen($filename,"r"); $str=""; while(!feof($f)) { $str .= fgets($f); } fclose($f); return $str; } function fpush($filename, $arr){ $f=fopen($filename, "a"); foreach ($arr as $str) { fwrite($f, NL . $str); // NL == "\r\n" } fclose($f); } function fnl($filename){ // add a new line "\r\n" in the file $f=fopen($filename, "a"); fwrite($f, NL); fclose($f); } function fclear($filename){ // clear a file file_put_contents($filename, ""); } function fempty($filename){ // is the file empty or not? $f = fopen($filename,"r"); fgetc($f); if (feof($f)) { return True;} else { return False;} fclose($f); }
The above introduces how to read PHP files into arrays, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.