phpmysqlcsvfputcsv

Add 1 Line with counter and change first with last Header using fputcsv in php


I wrote a little script which will take a CSV from a URL. Add a Row and import it into MySQL database.

All works fine but how can I change the content of Headline?

I use this to write my content into a New File.

$counter = 0;               
$data[53] = $counter++;
fputcsv($handle2,$data,$delimiter = ";", $enclosure = '"');

This will add a row with a counter after the last line of my CSV file. My CSV has no unique ID so I have to add one before I can import the CSV for my needs.

It works fine but I have to change some things via shell in CSV File directly but id should be done directly in Script.

The New added Line begins in first Headline with 0 but it should begin with something like uniqueid or another name and not with the counter value but I don't know how I should do that.

Instead of:

0
1
2
3++

I need something heading like:

uniqueid
1
2
3++

Also I want to change the Heading of $data[1] with the heading of $data[53]

if($loadfile == true){
    if (($handle1 = fopen("http://someurl.com/csv.csv", "r")) !== FALSE) {
        if (($handle2 = fopen("test.csv", "w")) !== FALSE) {
            while (($data = fgetcsv($handle1, 99999, ";", $enclosure = '"')) !== FALSE) {
                $data[] = $counter++;
                fputcsv($handle2,$data,$delimiter = ";", $enclosure = '"');
                   
            }
            fclose($handle2);
        }
        fclose($handle1);
        echo '<script type="text/javascript">alert("Succes ;)")</script>';
    }
}

Solution

  • So it's fairly simple

    if ($loadfile == true) {
        if (($handle1 = fopen("http://someurl.com/csv.csv", "r")) !== FALSE) {
            if (($handle2 = fopen("test.csv", "w")) !== FALSE) {
                $counter = 0;
                while (($data = fgetcsv($handle1, 99999, ";", $enclosure = '"')) !== FALSE) {
    
                    // if you want to have the id at the last column
                    $data[] = ($counter == 0) ? "uniqueid" : $counter;
    
                    // or alternatively for the id at the first column
                    //($counter == 0) ? array_unshift($data, "uniqueid") : array_unshift($data, $counter);
    
                    fputcsv($handle2,$data,$delimiter = ";", $enclosure = '"');
                    $counter++;
                }
                fclose($handle2);
            }
            fclose($handle1);
            echo '<script type="text/javascript">alert("Succes ;)")</script>';
        }
    }