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
PHP String Function to Get Substring Before the Last Occurrence of a Character
Get Size of Post-Request in PHP
PHP Syntax for Arrays: Different Behaviour Between PHP Versions
Redirect to Page and Send Custom Http Headers
Warning: MySQLi_Query() Expects Parameter 1 to Be MySQLi, String Given In
Laravel: Using Try...Catch with Db::Transaction()
How to Export a SQL Table Without Access to the Server or PHPmyadmin
How to Get the Unicode Value of a Character or Vise Versa with PHP
How to Detect Country/Location of Visitor
Curl and Https, "Cannot Resolve Host"
Convert Month from Name to Number
Why Is Crontab Not Executing My PHP Script
Get the Keys for Duplicate Values in an Array
How to Ceil, Floor and Round Bcmath Numbers
Are the PHP Preg_Functions Multibyte Safe
Remove Item from Array If It Exists in a 'Disallowed Words' Array