【问题标题】:How can I read 30MB text file using php script?如何使用 php 脚本读取 30MB 的文本文件?
【发布时间】:2011-01-31 15:51:03
【问题描述】:

您好,我确实有一个最大为 30MB 的文本文件,我想使用 PHP 循环脚本读取此文件

$lines = file('data.txt');

//loop through each line
foreach ($lines as $line) { \\some function }

有什么办法吗?我想打开它来阅读 php 不允许我打开一个 30MB 的文件。

【问题讨论】:

  • 你想对文件做什么?
  • 我想逐行读取,然后使用文本文件中的信息处理数据,然后插入 MySQl 数据库

标签: php file loops text


【解决方案1】:

你可以这样逐行阅读:

$file = fopen("data.txt", "r") or exit("Unable to open file!");

while(!feof($file)) {
  // do what you need to do with it - just echoing it out for this example
  echo fgets($file). "<br />";
}

fclose($file);

【讨论】:

  • 看到我的问题是 php 不允许我打开 30mb 文件。
  • 当你尝试做我发布的内容时它会说什么?
  • @leon cmets 不会给你任何帮助。它不工作不允许任何人帮助你。正如上面的海报所说,你必须告诉我们它在说什么。当您尝试运行该代码时会收到什么样的错误消息?
  • 我关闭了错误消息,因此它没有显示,而是一个空白页。我最初进行了测试,但没有意识到错误消息已被禁用,这导致了我的第一条评论。后来我发现从那时起缺少右括号,一切正常......
【解决方案2】:

逐行阅读:

$handle = fopen ("data.txt", "r"); 而 ( ( $buffer = fgets ( $handle, 4096 ) ) !== false ) { // 你的函数在线; }

【讨论】:

  • 你为什么要禁止警告? (@)
  • 对不起,坏习惯 - 已删除
【解决方案3】:

如果适合你逐段阅读文件,你可以试试这样的

$fd = fopen("fileName", "r");
while (!feof($fd)) {
$buffer = fread($fd, 16384); //You can change the size of the buffer according to the memory you can youse
//Process here the buffer, piece by piece
}
fclose($fd);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2010-09-14
    • 2015-12-11
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多