Quickest Way to Read First Line from File

2020-01-30 06:20发布

What's the quickest, easiest way to read the first line only from a file? I know you can use file, but in my case there's no point in wasting the time loading the whole file.

Preferably a one-liner.

标签: php file
10条回答
等我变得足够好
2楼-- · 2020-01-30 06:37

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));
查看更多
Lonely孤独者°
3楼-- · 2020-01-30 06:39

You could try to us fread and declare the file size to read.

查看更多
看我几分像从前
4楼-- · 2020-01-30 06:41
$firstline=`head -n1 filename.txt`;
查看更多
▲ chillily
5楼-- · 2020-01-30 06:41
$line = '';
$file = 'data.txt';
if($f = fopen($file, 'r')){
  $line = fgets($f); // read until first newline
  fclose($f);
}
echo $line;
查看更多
虎瘦雄心在
6楼-- · 2020-01-30 06:41
if(file_exists($file)) {
    $line = fgets(fopen($file, 'r'));
}
查看更多
对你真心纯属浪费
7楼-- · 2020-01-30 06:45

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.

查看更多
登录 后发表回答