Php implements the method of reading large files ,. Php implements the method of reading large files. Generally, when php reads large files, the method we use is generally a row of rows, instead of writing all files into the memory at one time, php can read large files,
Generally, when php reads large files, the method we use is generally to fetch a row, rather than writing all the files into the memory at a time, which will cause the php program to become stuck, the following is an example.
Read the last few rows of data from a large file:
<? Php/*** get the last $ n line of the file ** @ param string $ filename File path * @ param int $ n the last few lines * @ return mixed false indicates an error occurred, returns the string */function FileLastLines ($ filename, $ n) {if (! $ Fp = fopen ($ filename, 'r') {echo "failed to open the file. Please check whether the file path is correct and the path and file name do not contain Chinese characters"; return false ;} $ pos =-2; $ eof = ""; $ str = ""; while ($ n> 0) {while ($ eof! = "N") {if (! Fseek ($ fp, $ pos, SEEK_END) {$ eof = fgetc ($ fp); $ pos-;} else {break;} $ str. = fgets ($ fp); $ eof = ""; $ n-;} return $ str;} echo nl2br(FileLastLines('sss.txt ', 4 )); /***** get the last $ n lines of the file *** @ param string $ filename File path *** @ param int $ n the last few lines ** @ return mixed false indicates there are error, returns the string */function FileLastLines ($ filename, $ n) {if (! $ Fp = fopen ($ filename, 'r') {echo "failed to open the file. Please check whether the file path is correct and the path and file name do not contain Chinese characters"; return false ;} $ pos =-2; $ eof = ""; $ str = ""; while ($ n> 0) {while ($ eof! = "N") {if (! Fseek ($ fp, $ pos, SEEK_END) {$ eof = fgetc ($ fp); $ pos --;} else {break;} $ str. = fgets ($ fp); $ eof = ""; $ n --;} return $ str;} echo nl2br (FileLastLines ('sss. txt ', 4); function tail ($ fp, $ n, $ base = 5) {assert ($ n> 0); $ pos = $ n + 1; $ lines = array (); while (count ($ lines) <= $ n) {try {fseek ($ fp,-$ pos, SEEK_END );} catch (Exception $ e) {fseek (0); break;} $ pos * = $ base; while (! Feof ($ fp) {array_unshift ($ lines, fgets ($ fp) ;}} return array_slice ($ lines, 0, $ n );} var_dump (tail (fopen ("access. log "," r + "), 10); $ fp = fopen ($ file," r "); $ line = 10; $ pos =-2; $ t = ""; $ data = ""; while ($ line> 0) {while ($ t! = "N") {fseek ($ fp, $ pos, SEEK_END); $ t = fgetc ($ fp); $ pos -- ;}$ t = ""; $ data. = fgets ($ fp); $ line --;} fclose ($ fp); echo $ data;?>
Readers can improve and improve the instance based on its characteristics to better meet their application requirements.
Compile. Generally, when php reads large files, we use a single row instead of writing all the files into the memory at a time...