gpt4 book ai didi

php - 高效读取大文本文件

转载 作者:可可西里 更新时间:2023-11-01 13:47:04 26 4
gpt4 key购买 nike

我有几个巨大的(11mb54mb)文件,我需要读取这些文件来处理脚本的其余部分。目前我正在读取文件并将它们存储在一个数组中,如下所示:

$pricelist = array();
$fp = fopen($DIR.'datafeeds/pricelist.csv','r');
while (($line = fgetcsv($fp, 0, ",")) !== FALSE) {
if ($line) {
$pricelist[$line[2]] = $line;
}
}
fclose($fp);

.. 但我不断从我的虚拟主机那里收到内存过载消息。如何更有效地阅读它?

我不需要存储所有内容,我已经有了与数组键 $line[2] 完全匹配的关键字,我只需要读取那个数组/行。

最佳答案

如果您知道 key ,为什么不按 key 过滤掉呢?您可以使用 memory_get_usage() 函数检查内存使用情况,以查看在填充 $pricelist 数组后分配了多少内存。

echo memory_get_usage() . "\n";
$yourKey = 'some_key';
$pricelist = array();
$fp = fopen($DIR.'datafeeds/pricelist.csv','r');
while (($line = fgetcsv($fp, 0, ",")) !== FALSE) {
if (isset($line[2]) && $line[2] == $yourKey) {
$pricelist[$line[2]] = $line;
break;
/* If there is a possiblity to have multiple lines
we can store each line in a separate array element
$pricelist[$line[2]][] = $line;
*/
}
}
fclose($fp);
echo memory_get_usage() . "\n";

关于php - 高效读取大文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29288206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com