phpexcelphpexcelfgetcsvfputcsv

How to concatenate two columns in a csv file in php?


I have a csv file like this: enter image description here

I would like to concatenate the values of the style_color columns in this csv file. To have for example SCJEG4_1014. I wrote a script, it creates this last column with the header 'Pictures Names' but in each cell I just have "_".

How can I solve my problem?

<?php

//uploaded xlsx file recovery
$xlsx="C:/wamp64/www/Extract_pictures_Excel/xlsx_files/".date('Y_m_d H-i-s')."_file.xlsx";
move_uploaded_file($_FILES["mon_fichier"]["tmp_name"],$xlsx);

// Excel in CSV
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$excel = PHPExcel_IOFactory::load($xlsx);
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(";");
$writer->setEnclosure("");
$nomcsv = "C:/wamp64/www/Extract_pictures_Excel/csv/".date('Ymd_His').".csv";
$writer->save($nomcsv);

$delimiter = ";"; 
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
        $names_pictures = $data[7].'_'.$data[4];  
        $csv_data[] = $data;
        $row++;      
    }
    fclose($handle);
}

$extra_columns = array('Pictures Names' => $names_pictures);
foreach ($csv_data as $i => $data) {
    if ($i == 0) {
        $csv_data[$i] = array_merge($data, array_keys($extra_columns));
    } else {
        $csv_data[$i] = $data = array_merge($data, $extra_columns);
    }
}


if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
    foreach ($csv_data as $data) {
        fputcsv($handle, $data, $delimiter);
    }
    fclose($handle);
}


?>

Solution

  • It looks like you only add in the details from the last row ( as you only use the value of $names_pictures once). It would be better (IMHO) to add this value into the data at the point at which you generate the $csv_data array...

    while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
        $data['Pictures Names'] = $data[7] . '_' . $data[4];  
        $csv_data[] = $data;
        $row++;      
    }
    

    You could then remove the foreach ($csv_data as $i => $data) { loop

    If you had a different file for the output you could open the output file before the above loop and write the data directly to the output file rather than using $csv_data...

    if (($handle = fopen($nomcsv, 'r')) !== FALSE 
            && ($ohandle = fopen($nomcsvOutput, 'w')) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
            $data['Pictures Names'] = $data[7] . '_' . $data[4];  
            fputcsv($ohandle, $data, $delimiter);  
        }
        fclose($handle);
        fclose($ohandle);
    }