admin管理员组文章数量:1352828
good afternoon, I'm trying to read a csv file that is 9mb in size and contains about 40000 records. However I'm receiving this error Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 47464808 bytes). but my php.ini.overrides settings are: upload_max_filesize = 100M post_max_size = 108M This error occurs when I send the data to my view and try to display it.
//-->view code
<?php if (!empty($linhas)) : ?>
<div class="m-3 table-responsive text-nowrap mt-1"
style="min-height:50vh">
<div class="d-flex justify-content-center">
<h5 class="m-2">Dados do Arquivo</h5>
</div>
<table class="table table-striped table-bordered table-hover">
<thead class="table-light">
<tr>
<?php foreach ($linhas[0] as $coluna => $key) : ?>
<th class="text-center"><?= $coluna ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody class="table-border-bottom-0">
<?php foreach ($linhas as $linha) : ?>
<tr>
<?php foreach ($linha as $valor) : ?>
<td class="text-center"><?= $valor ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
//-->end view code
//-->php code
public static function processar(string $arquivo): array {
$finfo = new finfo();
if (base64_encode(base64_decode($arquivo, true)) === $arquivo) {
$conteudo = base64_decode($arquivo, true);
$ext = $finfo->buffer($conteudo, FILEINFO_MIME_TYPE);
} else {
$conteudo = fopen($arquivo, 'r');
if ($conteudo === false) {
throw new Exception('Erro ao abrir o arquivo.');
}
$ext = $finfo->file($arquivo, FILEINFO_MIME_TYPE);
}
$resultado = match ($ext) {
'text/csv' => self::csvFile($conteudo),
default => false
};
if (is_resource($conteudo)) {
fclose($conteudo);
}
if ($resultado === false) throw new Exception('O arquivo está vazio ou inválido!');
}
private static function csvFile($csv): array {
$data = [];
$keys = fgetcsv($csv);
while (($valores = fgetcsv($csv)) !== false) {
if (count($valores) === count($keys)) {
$linha = [];
for ($i = 0; $i < count($keys); $i++) {
$linha[$keys[$i]] = $valores[$i];
}
$data[] = $linha;
}
}
if (empty($data)) {
throw new Exception('O arquivo CSV está vazio ou inválido!');
}
return $data;
I'm sending this data to a view to generate a table with the csv. the error often happens in the view, but sometimes it also happens in the file where i show the code. Sorry for my bad English!
本文标签: Reading a 9mb csv file in phpMemory exhaustedStack Overflow
版权声明:本文标题:Reading a 9mb csv file in php - Memory exhausted - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743880237a2555064.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论