* 使用生成器处理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 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 )
}
}