1

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);
}
3
  • Third parameter of fgetcsv is a delimiter Commented Aug 2, 2017 at 9:10
  • Thanks for the answer. But could you explain it a bit more please? Commented Aug 2, 2017 at 9:25
  • 1
    Explain what? Commented Aug 2, 2017 at 9:39

1 Answer 1

2

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++;
}
Sign up to request clarification or add additional context in comments.

8 Comments

Yeah. This was really a great help. It works now. Thank you so much. :)
BTW. Is there also a way to remove also the first row of the new file?
You want the first row of the output file to be empty? Or you want to exclude the first line of the input file?
I want to exclude the first row completely. Because after i removed the columns the content of the new csv will be added to another csv. It works allready thanks to you and it's just a cosmetic thing. :)
i think we have a misunderstanding with rows and columns :) I think what u mean is that if one line of your csv is "param1;param2;param3;param4" you want to keep only "param2:param3:param4" of lines 1,2,4,5,8 right?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.