【问题标题】:Reading file PHP using too much memory使用太多内存读取文件 PHP
【发布时间】:2015-07-23 06:22:21
【问题描述】:

所以,我正在尝试解析一个包含 24MB 和 314134 行的文本文件。问题是,我觉得我的脚本使用了太多内存。

这是代码:

if(file_exists($filePath)) {
            $data = file_get_contents($filePath);

            $lines = explode("\n", $data);
            foreach ($lines as $line) {
                //Split the line.
                $spllitedLine = explode(';', utf8_encode($line));

                //Get the fields by their index.
                $localidade = !empty($spllitedLine[3]) ? $spllitedLine[3] : '';
                $codigo_postal = $spllitedLine[14] . '-' . $spllitedLine[15];

                $morada = (!empty($spllitedLine[5]) ? $spllitedLine[5] : ' ') . ' ' .
                    (!empty($spllitedLine[6]) ? $spllitedLine[6] : ' ') . ' ' .
                    (!empty($spllitedLine[7]) ? $spllitedLine[7] : ' ') . ' ' .
                    (!empty($spllitedLine[8]) ? $spllitedLine[8] : ' ') . ' ' .
                    (!empty($spllitedLine[9]) ? $spllitedLine[9] : '');

                //Create a new CTT location and save it to the Database.
                $location = new CttLocations();
                $location->address = preg_replace('/\s\s+/', ' ', $morada);
                $location->location = $localidade;
                $location->zipcode = $codigo_postal;
                $location->save(false);

                //Unset the variables to free space.
                unset($location);
                unset($line);
                unset($morada);
            }
        }

这当前使用了 153MB 的内存,甚至不在文件的一半中。我读过使用fopen() fgets() 和fclose() 是一个更好的解决方案,但我在这些方法中使用的内存量大致相同。我究竟做错了什么?我认为通过取消设置变量可以释放一些急需的空间。我认为 150MB 对于这样的操作来说太多了。有什么想法吗?

【问题讨论】:

  • 文件 I/O 可能而且非常昂贵。
  • 我的猜测是 PHP 和explode 语句的额外开销。您将每一行内容存储在一个数组中。所以这是 2x 24MB + 开销。

标签: php file memory


【解决方案1】:

这个:

 $data = file_get_contents($filePath);

对于大文件来说太重了。

这是你逐行读取文件的方式:

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
    }

    fclose($handle);
} else {
    // error opening the file.
} 

【讨论】:

    猜你喜欢
    • 2020-01-26
    • 2019-06-26
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2022-12-11
    • 2011-02-04
    相关资源
    最近更新 更多