phpcsv

Parse string from array to use in csv


I'm generating a array that record looks like:

315 => 
array (size=3)
  0 => string 'Bangkok ICD' (length=11)
  1 => string '[pc_315]' (length=8)
  2 => string '45.00;5600.00;677.78;45.00;454.00;;;;'

Next I'm putting this array in csv using simple method:

private function fill_file_data($list)
{
    $file = $this->csv_file_path."/tariff_{$this->freight_tariff->id}_matrix.csv";

    if (!file_exists($file))
    {
        file_put_contents($file, "");
    }

    $file_handler = fopen($file, 'w');

    foreach ($list as $fields)
    {
        fputcsv($file_handler, $fields, $this->delimiter, $this->separator);
    }

    fclose($file_handler);
    return;
}

But there is a problem with this part :

2 => string '45.00;5600.00;677.78;45.00;454.00;;;;'

It is separated by semicolon but fputcsv treats this as a string. Is there a way to read this part as csv columns?


Solution

  • I think you should explode your string by ; and add this values as new array elements, for example

    $arr = array(
        'Bangkok ICD',
        '[pc_315]',
        '45.00;5600.00;677.78;45.00;454.00;;;;'
    );
    $new_values = explode(';', $arr[2]);
    // now we remove string '45.00;5600.00;677.78;45.00;454.00;;;;'
    unset($arr[2]);
    $arr = array_merge($arr, $new_values);
    

    After that you can pass this item to your method.