: This article describes how to read PHP files into arrays. For more information about PHP tutorials, see. For ease of processing, I use fgets () to define a function that reads the content of a file into an array, where row I corresponds to the array I element (index is a i-1 ). Below 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;}
I use
str_replace("\r\n","",fgets($f))The reason is that fgets will also read in the line break, you can use count () to check the length of the string, it will be found that each row is read in the file corresponding to the line with two more characters. The equivalent program is
explode("\r\n", file_get_contents($filename))
Use the following code to restore an array to a (written) 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 your 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 describes how to read PHP files into arrays, including content, and hope to help those who are interested in PHP tutorials.