Jump to content

Best way to export PHP array into csv file


Recommended Posts

I am currently working on a simple task yet a bit tricky. My task is to read all the images from the directory and write them into CSV file. So, when I read the directory I get the array list of images filename data will look like below:

array (

I wanted this data to be exported into csv file which looks like below:


So, I am going through the foreach loop as $image which gives me each element and each loop I am checking the string has '-' character or not. If it has no '-' character than I assign $currentId = $image but if it has '-' then I append $additionalImage .= ', '.$image.'.jpg'. But I have an issue when accessing the $additionalImage. Below is my code what I have done so far.

$currentId = '';
$prevId = '';
$additionalImages = '';
$addId = '';
$counter = 0;

$file = fopen('./images/M2_import_image.csv', 'w');

foreach ($images as $image) {

    if (strpos($image, '-') == FALSE) {
        if ($currentId != $image) {
            $mainImage = $image.'.jpg';
            // print_r($additionalImages);
            fputcsv($file, array(
            $additionalImages = '';
        $currentId = $image;
        $additionalImages = $image.'.jpg';

    if (strpos($image, '-') != FALSE) {
        $addId = substr($image, 0, strpos($image, '-'));
        $additionalImages .= ', '.$image.'.jpg';



Link to comment
Share on other sites

  • Barand locked this topic
This topic is now closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.