for ease of handling, I used fgets () to define a function that reads the contents of the file into an array, and the first line of the file corresponds to the I element of the array (index is i-1). Here is the source code
function File2array ($filename) { //read a file into an array /per 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 the newline character, you can use count () to verify the length of the string, you will find each line read in the file in the corresponding line two characters more. The equivalent program is
Explode ("\ r \ n", file_get_contents ($filename))
Use the following code to restore the array to a (write) 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 manipulation 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 describes the PHP file read into the array, including the aspects of the content, I hope the PHP tutorial interested in a friend helpful.