对于我的项目之一,我需要导入一个非常大的文本文件(~ 950MB)。我在我的项目中使用 Symfony2 和 Doctrine 2。
我的问题是我收到如下错误:
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 24 bytes)
如果我将内存限制增加到 1GB,甚至会发生错误。
我试图通过使用 XDebug 和 KCacheGrind (作为 PHPEdit 的一部分)来分析问题,但我并不真正理解这些值:(
我正在寻找一种工具或方法(快速简单,因为我没有太多时间)来找出为什么内存被分配而不是再次释放。
编辑
在这里清除一些东西是我的代码:
$handle = fopen($geonameBasePath . 'allCountries.txt','r');
$i = 0;
$batchSize = 100;
if($handle) {
while (($buffer = fgets($handle,16384)) !== false) {
if( $buffer[0] == '#') //skip comments
continue;
//split parts
$parts = explode("\t",$buffer);
if( $parts[6] != 'P')
continue;
if( $i%$batchSize == 0 ) {
echo 'Flush & Clear' . PHP_EOL;
$em->flush();
$em->clear();
}
$entity = $em->getRepository('MyApplicationBundle:City')->findOneByGeonameId( $parts[0] );
if( $entity !== null) {
$i++;
continue;
}
//create city object
$city = new City();
$city->setGeonameId( $parts[0] );
$city->setName( $parts[1] );
$city->setInternationalName( $parts[2] );
$city->setLatitude($parts[4] );
$city->setLongitude( $parts[5] );
$city->setCountry( $em->getRepository('MyApplicationBundle:Country')->findOneByIsoCode( $parts[8] ) );
$em->persist($city);
unset($city);
unset($entity);
unset($parts);
unset($buffer);
echo $i . PHP_EOL;
$i++;
}
}
fclose($handle);
我尝试过的事情,但没有任何帮助:
- 将第二个参数添加到fgets
- 增加 memory_limit
- 取消设置变量