最小的内存密集的方式来读取PHP中的文件 [英] Least memory intensive way to read a file in PHP

查看:134
本文介绍了最小的内存密集的方式来读取PHP中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Php中的file()函数读取包含大约50k行的文件。但是,由于文件的内容作为数组存储在存储器中,所以它的内存不足错误。有没有其他的方法?

I am reading a file containing around 50k lines using the file() function in Php. However, its giving a out of memory error since the contents of the file are stored in the memory as an array. Is there any other way?

另外,存储的行的长度是可变的。

Also, the lengths of the lines stored are variable.

这里是代码。另外文件是700kB不是mB。

Here's the code. Also the file is 700kB not mB.

private static function readScoreFile($scoreFile)
{
    $file = file($scoreFile);
    $relations = array();

    for($i = 1; $i < count($file); $i++)
    {
        $relation = explode("\t",trim($file[$i]));
        $relation = array(
                        'pwId_1' => $relation[0],
                        'pwId_2' => $relation[1],
                        'score' => $relation[2],
                        );
        if($relation['score'] > 0)
        {
            $relations[] = $relation;
        }
    }

    unset($file);
    return $relations;
}


推荐答案

使用 fopen fread fclose 顺序读取文件:

Use fopen, fread and fclose to read a file sequentially:

$handle = fopen($filename, 'r');
if ($handle) {
    while (!feof($handle)) {
        echo fread($handle, 8192);
    }
    fclose($handle);
}

这篇关于最小的内存密集的方式来读取PHP中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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