There is a very convenient way to read files in Python:
for line in open('file'): print line
A similar notation in PHP? Like Python, two lines?
Reply content:
There is a very convenient way to read files in Python:
for line in open('file'): print line
A similar notation in PHP? Like Python, two lines?
Of course, please refer to the example of file ():
foreach(file('file') as $line) echo $line;
@ Childe's answer is the standard answers
However, assuming that the file is large, then there is actually a performance problem, which will make PHP larger memory, the file is large enough to cause serious errors
Thankfully, starting with the PHP 5.5.0 release, the new feature Generator generator is definitely a better solution
function getLines($file) { $f = fopen($file, 'r'); try { while ($line = fgets($f)) { yield $line; } } finally { fclose($f); }}foreach (getLines("file.txt") as $n => $line) { if ($n > 5) break; echo $line;}
The introduction of the generator is here Generator
Use generator, save memory, Absolute good
The two lines are uncertain, at least four rows.
//读文件$fh = fopen('file', 'r');//如果指针没在文件末尾继续while (!feof($fh)) { //输出当前行并将指针移动到下一行 echo fgets($fh) . "\r\n";}fclose($fh);
In these four rows, if the file read fails, we can handle it, and your two lines want to determine this, and you need to change back to four rows.
You know what I mean,
In fact, Python can line up files on a single line, such as:
array = [INT (Line.strip ()) for line in open (' file ')]
Python3 joined with open (' file ') F.close can not write.
It doesn't make any sense than the number of rows. This is too simple in PHP.
$fp = fopen('file', 'r');while($line = fgets($fp)) { echo $line;}