我有一個2Mb大小的csv文件,並且有管道分隔符。我想取第一行並替換它的數據,然後重新保存文件。下面是我做的:在PHP中替換CSV行,內存錯誤
//Creating a new first row with the modified data.
$file = fopen($path,"r");//$path is where the file is located : outputs/my_file.csv
$size = filesize($path);
$firstLine = fgetcsv(fopen($path,"r")); //$firstLine has all the data of the first row as array
fclose($file);
$firstLine = explode("|", $firstLine[0]);//To get each column row
$newHeader = array();
for($i = 0; $i<sizeof($firstLine); $i++){
if($i == 4){
array_push($newHeader, "modified column in row 1 ");//Only column 4 in row 1 is modified
}else{
array_push($newHeader, $firstLine [$i]);
}
}
$Header = implode("|", $newHeader);
//Creating the new csv file
$row = 0;
while (($data = fgetcsv(fopen($path,"r"), "|")) !== false) {
if($row == 0){
$data[0] = $Header;
}
$newCsvData[] = $data;
}
return $newCsvData; //I wanted to display the new content of the csv before saving it
此代碼應打印csv文件的新內容,我會保存,但我得到一個錯誤:用盡536870912個字節允許內存大小(試圖分配332個字節),如何能我以非常快的方式做到這一點?該文件大約是19122行。
感謝
是的我使用類似於你的解決方案修復它,謝謝。 – 2014-09-23 19:29:50