PHP – Add data to CSV file in specific columns

Base on the requirement of my client, I have to create a CSV file which has a lot of columns, and hundreds of rows.

The header looks like this:

SKU | category | description | image | small_image | thumbnail | price | color

I need to read the data from other files and put the suitable data in the correct column.

I tried many different ways but it didn’t work. Finally, I found out a way to do it quickly, here is how I did with PHP:

At first, I break out the columns into an array precisely as they appear in the raw CSV file:

$columns = ["sku","category","description","image","small_image","thumbnail", "price","color"];

Then I open the file and iterate over it, building an associative array of key-value pairs, checking whether or not a file exists for that image name, and if so, assigning the correct name to the array.

$rootDir = ""; //Root directory where the image files are located
$file = fopen("filehandle.csv", "r"); //Open the old file for reading
$newFile = fopen("newfilehandle.csv", "w"); //Create a new file for writing

while (($data = fgetcsv($file)) !== FALSE) {
    $row = array_combine($columns, $data);
    $filename = "{$row['sku']}.jpeg";
    if (file_exists("$rootDir/$filename")) {
        $row['image'] = $filename;
        $row['small_image'] = $filename;
        $row['thumbnail'] =  $filename; 
    }
    fputcsv($newFile, array_values($row)); //Write data into new file
}

fclose($file);
fclose($newFile);

Hope it is useful to you 🙂

Revisions

No comments yet.

Leave a Reply