Php: Read Specific Line from File

PHP: Read Specific Line From File

$myFile = "4-24-11.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2

file — Reads entire file into an array

Reading specific line of a file in PHP

Use SplFileObject::seek

$file = new SplFileObject('yourfile.txt');
$file->seek(123); // seek to line 124 (0-based)

Reading Specific Lines In Text File With PHP

Use while, fopen and feof (it is good for read big files 8) ), like this:

<?php
function retrieveText($file, $init, $end, $sulfix = '')
{
$i = 1;
$output = '';

$handle = fopen($file, 'r');
while (false === feof($handle) && $i <= $end) {
$data = fgets($handle);

if ($i >= $init) {
$output .= $data . $sulfix;
}
$i++;
}
fclose($handle);

return $output;
}

Example on how to use this function to get lines 51 to 100 :

echo retrieveText('myfile.txt', 51, 100);

Add break line:

echo retrieveText('myfile.txt', 51, 100, PHP_EOL);

Add break line in html:

echo retrieveText('myfile.txt', 51, 100, '<br>');

How to read specific lines from a text file in PHP

Just use descriptor

$fd = fopen($file, 'r');
$head = fgets($fd);
$headValues = explode(',', $head);
$data = [];

while(($str = fgets($fd)) !== false) {
$otherValues = explode(',', $str);
$data[] = $otherValues;
}

Read File to specific line php

Try to use this function you should use iteration and get line by range.

$file = new SplFileObject('yourfile.txt');

echo getLineRange(1,10000);

function getLineRange($start,$end){
$tmp = "";

for ($i = $start; $i <= $end; $i++) {
$tmp .= $file->seek($i);
}
return($tmp);
}

PHP: Read specific lines in a large file (without reading it line-by-line)

Using splfileobject

  • no need to read all lines 1 by 1

  • can "jump" to desired line

In the case you know the line number :

//lets say you need line 4
$myLine = 4 ;
$file = new SplFileObject('bigFile.txt');
//this is zero based so need to subtract 1
$file->seek($myLine-1);
//now print the line
echo $file->current();

check out :
http://www.php.net/manual/en/splfileobject.seek.php



Related Topics



Leave a reply



Submit