Home > Article > Backend Development > What is the code for php to read the last few lines of data from the file?
In PHP, you can use the file() and array_slice() functions to read the last few lines of data in the file and implement the code "array_slice(file($file,FILE_IGNORE_NEW_LINES), - number of lines)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php Read the last few lines of data from the file
Implementation idea:
Use the file() function to store the entire file data into an array, each line The data corresponds to an array element
. Just use the array_slice() function to get the last few elements in the array.
Implementation code:
<?php header("Content-Type: text/html;charset=utf-8"); //设置字符编码 $file = 'test.txt'; $filearr = file($file,FILE_IGNORE_NEW_LINES); echo "文件的数据:"; var_dump($filearr); echo "截取数组后2位的元素片段:"; $result = array_slice($filearr,-2); //截取数组后2位的元素 var_dump($result); ?>
Output result:
Description:
file()
The function will store the contents of the file into an array line by line (including newlines). This array is returned on success, FALSE on failure. The syntax format of the file() function is as follows:
file($filename,$flags,$context)
This function accepts one required parameter $filename
(the file to be read), and two omitted parameters $flags
and $context
(the environment of the file handle).
But generally the $flags
parameter is still set, which can be one or more of the following constants:
##FILE_USE_INCLUDE_PATH: Search for files in include_path (in php.ini), the default is FALSE; if you want, set the parameter value to '1'.
FILE_IGNORE_NEW_LINES: Do not add a newline character at the end of each element of the array;
FILE_SKIP_EMPTY_LINES: Skip empty lines.
array_slice() function is a function provided by PHP to intercept an array, and can extract a fragment from the array. The syntax is as follows:
array array_slice ( array $arr , int $start [, int $length = NULL [, bool $preserve_keys = false ]] )Parameter description:
PHP Video Tutorial"
The above is the detailed content of What is the code for php to read the last few lines of data from the file?. For more information, please follow other related articles on the PHP Chinese website!