Question

I'm using the code below for adding data into a csv file based on a import from a csv file. When I write the new data to a new csv file everything looks ok! But I would like to append the new data into new columns. I will try to explain with a example.

The first column of the original csv contains Id's. These id's are used to obtain data from a remote website. This data is saved into an array called csv_array(); :

$id = array();
if (($handle = fopen($filename, 'r')) !== false)
{
    while (($data = fgetcsv($handle, 1000, ";")) !== false)
    {
        if ($data[0] != null)
        {
            $id[] = $data[0];
        }
    }
    fclose($handle);
}

$csv_array = array();
foreach ($id as $product_id)
{
     array_push($csv_array, $arr = array_merge(array('id' => $product_id), $product_info, $images));
}

The next step is to insert this data into a new .csv file.

function export($csv_array)
{
    $filename = "info.csv";
    $fp = fopen($filename, 'w');
    fputcsv($fp, array_keys($csv_array[0]), ';');
    foreach ($csv_array as $fields)
    {
        fputcsv($fp, $fields, ';');
    }
    fclose($fp);
}

This all works but I would like to append the new data into three new columns into the original csv. I tryed using $fp = fopen($filename, 'a'); but this appends the new data in the end of the csv instead of three new columns. Who can give me a hint :)

Was it helpful?

Solution

You will want to add the new columns to $csv_array (before you call fputscsv). The best place to add them in your code would be here:

$csv_array = array();
foreach ($id as $product_id)
{
    array_push(
       $csv_array,
       $arr = array_merge(array('id' => $product_id), $product_info, $images, $your_new_columns_for_this_row)
    );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top