Heim  >  Artikel  >  Backend-Entwicklung  >  PHP按行读取、处理较大CSV文件的例子

PHP按行读取、处理较大CSV文件的例子

WBOY
WBOYOriginal
2016-07-25 08:53:381021Durchsuche
  1. /**
  2. * csv_get_lines 读取CSV文件中的某几行数据
  3. * @param $csvfile csv文件路径
  4. * @param $lines 读取行数
  5. * @param $offset 起始行数
  6. * @return array
  7. * */ bbs.it-home.org
  8. function csv_get_lines($csvfile, $lines, $offset = 0) {
  9. if(!$fp = fopen($csvfile, 'r')) {
  10. return false;
  11. }
  12. $i = $j = 0;
  13. while (false !== ($line = fgets($fp))) {
  14. if($i++ continue;
  15. }
  16. break;
  17. }
  18. $data = array();
  19. while(($j++ $data[] = fgetcsv($fp);
  20. }
  21. fclose($fp);
  22. return $data;
  23. }
复制代码

调用方法:

  1. $data = csv_get_lines('path/bigfile.csv', 10, 2000000);
  2. print_r($data);
复制代码

函数主要采用行定位的思路,通过跳过起始行数来实现文件指针定位。 上述函数对500M以内的文件进行过测试,运行通畅,对于更大的文件未做测试,请斟酌使用或加以改进。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn