gpt4 book ai didi

php - 读取大文件时出现内存不足错误

转载 作者:可可西里 更新时间:2023-11-01 12:46:22 25 4
gpt4 key购买 nike

我有一个大的 csv,我想解析并插入到我的数据库中。我有这个 PHP:

$target = '../uploads/'.$f;
$handle = fopen($target, "r");
$data = fgetcsv($handle, 0, ",");

$rows = array();

while ($data !== FALSE) {
$rows[] = $data;
}

fclose($handle);

if (count($rows)) {
foreach ($rows as $key => $value) {

echo $value;

}
}

每次我尝试运行我的脚本时,我都会收到此错误:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 35 bytes)

有什么办法吗?

最佳答案

我认为这部分是错误的:

$data = fgetcsv($handle, 0, ",");
$rows = array();
while ($data !== FALSE) {
$rows[] = $data;
}

一次调用 fgetcsv$handle 读取一行。您需要将 fgetcsv 放在循环条件中:

$handle = fopen($target, "r");
$data = fgetcsv($handle, 0, ",");
while (($row = fgetcsv($handle, 0, ",")) !== FALSE) {
// Example insert - obviously use prepared statements/escaping/another DAL
$db->query("INSERT INTO tbl (columns..) VALUES ({$row[0]}, {$row[1]} ... )");
}

关于php - 读取大文件时出现内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8441469/

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