automatically delete columns from a csv file
Her开发者_如何学编程e's my problem: I need to automatically delete specific columns from a csv file before parsing it using fgetcsv in php. If I don't delete those columns (which i really don't need), i get an out of memory error. Thanks!
I don't know if commandline is an option but if so the cut
command will save your day. If you are running low on memory you might want to process your csv with cut
before actually loading it with php.
my.csv
a;b;c;d;
0;1;2;3;
0;1;2;3;
0;1;2;3;
0;1;2;3;
0;1;2;3;
0;1;2;3;
0;1;2;3;
0;1;2;3;
0;1;2;3;
Command: removes the third column
cut -d ";" -f1-2,4- my.csv
Output
a;b;d;
0;1;3;
0;1;3;
0;1;3;
0;1;3;
0;1;3;
0;1;3;
0;1;3;
0;1;3;
0;1;3;
Using a simple php script you could unset the field to remove it from the output file.
This example removes the 2nd field from the $inFile
and saves the result in the $outFile
<?php
$read = fopen($inFile, 'r');
$write = fopen($outFile, 'w');
if ($write && $read) {
while (($data = fgetcsv($read)) !== FALSE) {
unset($data[1]);
fputcsv($write, $data);
}
}
fclose($write);
fclose($read);
If you are having memory issues though, a better alternative may be to write a script to move the data into a database, then you can query for just the data and fields that you need.
精彩评论