Does the PHP open file have a python-like "for lines in open (' file ') notation?"

Source: Internet
Author: User
Tags generator generator php open file
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;}
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.