码迷,mamicode.com
首页 > Web开发 > 详细

Modern PHP 使用生成器处理csv文件 Generator

时间:2018-07-15 14:58:58      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:and   out   pen   output   key   send   hand   ===   ==   

* 使用生成器处理csv文件

 

<?php
function getRows($file) {
    $handle = fopen($file, ‘rb‘);
    if ($handle === false) {
        throw new Exception(‘open file ‘.$file.‘ error‘);
    }
    while (feof($handle) === false) {
        yield fgetcsv($handle);
    }
    fclose($handle);
}

// 只会为csv文件中的一行分配内存
// 不需要把整个csv文件都读取到内存
$generator = getRows(‘../data/t_video.csv‘);

// foreach ($it as $row) {print_r($row);}
while ($generator->valid()) {
    print_r($generator->current());
    $generator->next();
}
$generator->rewind();

// http://php.net/manual/en/class.generator.php

  

input: ../data/t_video.csv

"9","其他","ULTIMATE PHOTO GUIDE",NULL,"http://118.190.209.209/media/mp4/1.mp4","http://118.190.209.209/media/png/1.png","ULTIMATE PHOTO GUIDE"
"10","其他","THE VERGE",NULL,"http://118.190.209.209/media/mp4/2.mp4","http://118.190.209.209/media/png/2.the_verge.png","THE VERGE"
"11","其他","Microsoft Power BI",NULL,"http://118.190.209.209/media/mp4/3.mp4","http://118.190.209.209/media/png/3.png","Microsoft Power BI"

  

output:

Array
(
    [0] => 29
    [1] => 龙都教育
    [2] => 龙都教育_第3期
    [3] => NULL
    [4] => http://118.190.209.209/media/mp4/%E9%BE%99%E9%83%BD%E6%95%99%E8%82%B21103VA0.mp4
    [5] => http://118.190.209.209/media/poster/puyang_longdu_edu_1103.jpg
    [6] => 龙都教育第3期20171103 濮阳市第一实验小学学生 范子恒
)
Array
(
    [0] => 30
    [1] => 课程
    [2] => 青春的情绪-濮阳范县-刘艳艳
    [3] => NULL
    [4] => http://118.190.209.209/media/mp4/puyang/%E5%88%98%E8%89%B3%E8%89%B31_2017_6_12_17_6_32_2f45_0.mp4
    [5] => http://118.190.209.209/media/poster/puyang/puyang01_liuyanyan_youth_emotion.jpg
    [6] => 青春的情绪. 做游戏:抓手指
)

 

Generator:

Generator implements Iterator {
  /* Methods */
  public mixed current ( void )
    public mixed getReturn ( void )
    public mixed key ( void )
    public void next ( void )
    public void rewind ( void )
    public mixed send ( mixed $value )
    public mixed throw ( Throwable $exception )
    public bool valid ( void )
    public void __wakeup ( void )
  }
}

  

  

  

 

Modern PHP 使用生成器处理csv文件 Generator

标签:and   out   pen   output   key   send   hand   ===   ==   

原文地址:https://www.cnblogs.com/mingzhanghui/p/9313389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!