PHP开发很多时候都要读取大文件,比如csv文件、text文件等。这些文件如果很大,比如10个G。这时,直接一次性把所有的内容读取到内存中计算不太现实。
遇到这种情况,往往觉得PHP太弱,实则不然。利用生成器(关键字yield)就能解决。
好了,上代码。
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2017/12/8 * Time: 22:05 */ header("content-type:text/html;charset=utf-8"); function readCvs() { # code... $handle = fopen("./test.csv", 'rb'); while (feof($handle)===false) { # code... yield fgetcsv($handle); } fclose($handle); } $result = readCvs(); foreach ($result as $key => $value) { echo "<pre>"; var_dump( $value); echo "</pre>"; // exit; }
相关资料:
http://php.net/manual/zh/language.generators.overview.php
https://www.cnblogs.com/tingyugetc/p/6347286.html