phpfileline

How to read specific lines from a text file in PHP


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


Solution

  • Just use descriptor

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