Reading file PHP using too much memory -
so, i'm trying parse text file has 24mb , 314134 lines. problem is, feel script using way memory.
this code:
if(file_exists($filepath)) { $data = file_get_contents($filepath); $lines = explode("\n", $data); foreach ($lines $line) { //split line. $spllitedline = explode(';', utf8_encode($line)); //get fields index. $localidade = !empty($spllitedline[3]) ? $spllitedline[3] : ''; $codigo_postal = $spllitedline[14] . '-' . $spllitedline[15]; $morada = (!empty($spllitedline[5]) ? $spllitedline[5] : ' ') . ' ' . (!empty($spllitedline[6]) ? $spllitedline[6] : ' ') . ' ' . (!empty($spllitedline[7]) ? $spllitedline[7] : ' ') . ' ' . (!empty($spllitedline[8]) ? $spllitedline[8] : ' ') . ' ' . (!empty($spllitedline[9]) ? $spllitedline[9] : ''); //create new ctt location , save database. $location = new cttlocations(); $location->address = preg_replace('/\s\s+/', ' ', $morada); $location->location = $localidade; $location->zipcode = $codigo_postal; $location->save(false); //unset variables free space. unset($location); unset($line); unset($morada); } }
this using 153mb of memory , it's not in half of file. i've read using fopen()
fgets()
, fclose()
it's better solution using same amount of memory methods. doing wrong? thought unsetting variables free needed space. think 150mb way operation this. thouhgts?
this :
$data = file_get_contents($filepath);
is way heavy big files.
this how read file line line :
$handle = fopen("inputfile.txt", "r"); if ($handle) { while (($line = fgets($handle)) !== false) { // process line read. } fclose($handle); } else { // error opening file. }
Comments
Post a Comment