I need to remove some columns and the first row from a csv and put the result in a new csv file. I tried already with some sugesstions found here on stack, but none of them will work for me. My csv has 9 columns but i only need 5 of them. The best found solution here to remove the columns seems to be the one i will post below, but i only get commas in the result file and some where some data. The data in my csv are spararted with ';' I hope any one can help me.
Here is the code i played with:
<?php
$input = 'gesamtbestand.csv';
$output = 'mw-stock.csv';
if (false !== ($ih = fopen($input, 'r'))) {
$oh = fopen($output, 'w');
while (false !== ($data = fgetcsv($ih))) {
// this is where you build your new row
$outputData = array($data[1], $data[2], $data[4], $data[5], $data[8]);
fputcsv($oh, $outputData);
}
fclose($ih);
fclose($oh);
}
The default delimiter for fgetcsv is , as you can see in php manual http://php.net/manual/en/function.fgetcsv.php
If your csv file uses ; for delimiter then you should change the line
while (false !== ($data = fgetcsv($ih))) {
to
while (false !== ($data = fgetcsv($ih, 0, ";"))) {
The default enclosure is "
if you don't use an enclosure in your data then you should change the line to
while (false !== ($data = fgetcsv($ih, 0, ";", ""))) {
As for excluding the first entry of the csv file you can do this
$i=0;
while (false !== ($data = fgetcsv($ih))) {
// this is where you build your new row
if ($i!=0){
$outputData = array($data[1], $data[2], $data[4], $data[5], $data[8]);
fputcsv($oh, $outputData);
}
$i++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.