Software Developer

PHP Function To Get a Few Lines From a Large Data Text File

This is a useful PHP function when you just need to pull a few lines from a very large data text file. For example, say you have a text file full of 1.5 GB of data, and you don’t want to open the file because it’s so large, but you just want to see a few lines in order to inspect the structure of the data. For whatever reason, in some cases, this may be your quickest way to analyze and determine the data structure for that text file.

This PHP function will get a few lines from a data file so that you can view those lines. You must specify how many lines you want to get. It accepts 3 parameters:

  1. $file – (string) The path to the file. Required.
  2. $lines – (int) The number of lines that you want to get. Required.
  3. $return – (bool) Optional. Whether to return instead of echo the results. Default is false. Set it to true if you want to return the results to PHP instead of displaying them on the screen.

 * Get some lines from a data file. Useful for when you need to determine the structure of a very large data file. Just pass the path to the file, and the number of lines to show.
 * @param string $file The path to the file
 * @param int $lines The number of lines to show.
 * @param bool $return Whether to return instead of echo the results.
function isa_get_few_lines_from_datafile($file, $lines, $return = false) {
	$out = '';
	$handle = @fopen($file,'r');
	if (false === $handle) {
		$out .= "ERROR: missing file ($file)";
	} else {
		$c = 0;
		while(($v = fgets($handle, 4096))!==false) {
			if (!trim($v)) continue;// skip blank lines
			if($c <= $lines) {
				$out .= $v . '<hr />';
 	if ( $return ) {
		return $out;
	} else {
		echo $out;

Usage example

The following example will get 4 lines from a file called, datafile.txt which is in a Downloads directory. It will print the results to the screen.

isa_get_few_lines_from_datafile("/home/user/Downloads/datafile.txt", 4);

To return the results to use in PHP instead of displaying them, set the third parameter to true, like this:

isa_get_few_lines_from_datafile("/home/user/Downloads/datafile.txt", 4, true);


Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this: