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

查看:16
本文介绍了在 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("	",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;
}

推荐答案

使用 fopenfreadfclose 顺序读取文件:

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天全站免登陆