This article mainly introduces the php method for reading large files. For more information about how to read large files in php, we usually use one row to read large files, instead of writing all files to the memory at a time, this 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.