Quickest Way to Read First Line from File

$firstline=`head -n1 filename.txt`;

$line = '';
$file = 'data.txt';
if($f = fopen($file, 'r')){
  $line = fgets($f); // read until first newline
  fclose($f);
}
echo $line;

I'm impressed no one mentioned the file() function:

$line = file($filename)[0];

or if version_compare(PHP_VERSION, "5.4.0") < 0:

$line = array_shift(file($filename));

Well, you could do:

$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);

It's not one line, but if you made it one line you'd either be screwed for error checking, or be leaving resources open longer than you need them, so I'd say keep the multiple lines

Edit

If you ABSOLUTELY know the file exists, you can use a one-liner:

$line = fgets(fopen($file, 'r'));

The reason is that PHP implements RAII for resources.

That means that when the file handle goes out of scope (which happens immediately after the call to fgets in this case), it will be closed.

Tags:

Php

File