我在PHP中解析1 000 000行csv文件以恢复此数据:使用的IP地址,DNS,密码套件。 为了知道某些DNS(具有多个邮件服务器)是否在其服务器上使用了不同的密码套件,我必须在数组中存储包含DNS名称的对象,其服务器的IP地址列表以及他使用的密码套件。最后,我有一个1 000 000元素的数组。要了解在其服务器上具有不同密码套件配置的DNS的数量,我会这样做:
foreach($this->allDNS as $dnsObject){
$res=0;
if(count($dnsObject->getCiphers()) > 1){ //if it has several different config
res++;
}
return $res;
}
问题:消耗太多内存,我无法在1000000行csv上运行我的代码(如果我不将这些数据存储在数组中,我会在20秒内解析此csv文件...) 。有没有办法绕过这个问题?
注意:我已经把
了ini_set('memory_limit', '-1');
但这一行只是绕过了内存错误。
答案 0 :(得分:1)
答案 1 :(得分:0)
将处理后的数据(每行单独写入)写入一个文件(或数据库)
file_put_contents('data.txt', $parsingresult, FILE_APPEND);
FILE_APPEND会将$ parsingresult附加到文件内容的末尾。
然后,您可以通过file_get_contents()或file()来访问已处理的数据。
反正。我认为,如果需要更频繁地使用数据库和一些预处理将是最好的解决方案。
答案 2 :(得分:0)
您可以使用fgetcsv()
一次一行地读取和解析CSV文件。保留您需要的数据并丢弃该行:
// Store the useful data here
$data = array();
// Open the CSV file
$fh = fopen('data.csv', 'r');
// The first line probably contains the column names
$header = fgetcsv($fh);
// Read and parse one data line at a time
while ($row = fgetcsv($fh)) {
// Get the desired columns from $row
// Use $header if the order or number of columns is not known in advance
// Store the gathered info into $data
}
// Close the CSV file
fclose($fh);
这样它就会使用解析CSV文件所需的最小内存量。