Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read specific lines from a text file in PHP

Tags:

file

php

line

I have a txt file which has a lot of lines and the values in every line are separated with commas.

I want to read the 1st line alone which I did already using fgets :

$head = fgets(fopen($file, 'r'));
$headValues = explode(',', $head);

but now I want to read every other line from line 2 until the end of file and put those values into an array.

I searched for similar solutions but couldn't find any

like image 913
dragi Avatar asked Jan 28 '26 06:01

dragi


2 Answers

Just use descriptor

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

while(($str = fgets($fd)) !== false) {
  $otherValues = explode(',', $str); 
  $data[] = $otherValues;
}
like image 142
shukshin.ivan Avatar answered Jan 29 '26 21:01

shukshin.ivan


This uses fgetcsv for the lines you care about and uses array_combine to put the headers and the line data together.

$fh = fopen($file, 'r');
$headValues = fgetcsv($fh);
$data = [];
while (true)    {
    if ( ($values = fgetcsv($fh)) === false ) {
        break;
    }
    $data[] = array_combine($headValues, $values);
    if ( fgets($fh) === false ) {
        break;
    }
}
fclose($fh);
print_r($data);

It checks at each read in case the EOF has been reached and then breaks out of the read loop.

like image 37
Nigel Ren Avatar answered Jan 29 '26 21:01

Nigel Ren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!