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:49

Try this:

$file = 'data.txt';
$data = file_get_contents($file);
$lines = explode
查看更多
仙女界的扛把子
3楼-- · 2020-01-30 06:52

In one of my projects (qSandbox) I uses this approach to get the first line of a text file that I read anyways. I have my email templates are in a text files and the subject is in the first line.

$subj_regex = '#^\s*(.+)[\r\n]\s*#i';

// subject is the first line of the text file. Smart, eh?
if (preg_match($subj_regex, $buff, $matches)) {
    $subject = $matches[1];
    $buff = preg_replace($subj_regex, '', $buff); // rm subject from buff now.
}
查看更多
霸刀☆藐视天下
4楼-- · 2020-01-30 07:00

fgets() returns " " which is a new line at the end,but using this code you will get first line without the lineBreak at the end :

$handle = @fopen($filePath, "r");
$text=fread($handle,filesize($filePath));
$lines=explode(PHP_EOL,$text);
$line = reset($lines);
查看更多
可以哭但决不认输i
5楼-- · 2020-01-30 07:02

If you don't mind reading in the entire file, then a one-liner would be:

$first_line = array_shift(array_values(preg_split('/\r\n|\r|\n/', file_get_contents($file_path), 2)));

:)

查看更多
登录 后发表回答