如何在PHP中读取巨大的文本文件? [英] How to read giant text file in PHP?

查看:219
本文介绍了如何在PHP中读取巨大的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个文本文件的大小超过 30MB



如何读取这样巨大的文本文件from PHP?

解决方案

除非您需要在同一时间处理所有数据,否则可以分段读取它们。二进制文件示例:

 <?php 
$ handle = fopen(/ foo / bar / somefile ,rb);
$ contents ='';
while(!feof($ handle)){
$ block = fread($ handle,8192);
do_something_with_block($ block);
}
fclose($ handle);
?>上面的例子可能会破坏多字节编码(如果在8192字节的边界上有一个多字节字符 - 例如UTF-8中的Ǿ),所以对于具有有意义的结束符的文件(例如文本),试试这个:

 <?php 
$ handle = fopen(/ foo / bar / somefile,rb);
$ contents ='';
while(!feof($ handle)){
$ line = fgets($ handle);
do_something_with_line($ line);
}
fclose($ handle);
?>


I have few text files with size more than 30MB.

How can i read such giant text files from PHP?

解决方案

Unless you need to work with all the data at the same moment, you can read them in pieces. Example for binary files:

<?php
$handle = fopen("/foo/bar/somefile", "rb");
$contents = '';
while (!feof($handle)) {
  $block = fread($handle, 8192);
  do_something_with_block($block);
}
fclose($handle);
?>

The above example might break multibyte encodings (in case there's a multibyte character across the 8192-byte boundary - e.g. Ǿ in UTF-8), so for files that have meaningful endlines (e.g. text), try this:

<?php
$handle = fopen("/foo/bar/somefile", "rb");
$contents = '';
while (!feof($handle)) {
  $line = fgets($handle);
  do_something_with_line($line);
}
fclose($handle);
?>

这篇关于如何在PHP中读取巨大的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆