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
- February 9, 2018 @ 11:56:33 [Current Revision] by Sharing Solution
- February 9, 2018 @ 11:56:33 by Sharing Solution
- January 2, 2018 @ 18:24:00 by Sharing Solution
- January 2, 2018 @ 18:22:52 [Autosave] by Sharing Solution
- January 2, 2018 @ 18:21:44 by Sharing Solution
- January 2, 2018 @ 18:20:38 by Sharing Solution
- January 2, 2018 @ 18:20:15 by Sharing Solution
- January 2, 2018 @ 18:19:28 by Sharing Solution
- January 2, 2018 @ 18:18:39 by Sharing Solution
- January 2, 2018 @ 18:11:28 by Sharing Solution
No comments yet.