Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fputcsv() add quotes to every entry?

With this code I create my CSV export file:

foreach ($data_for_export as $row) {
    $data = [];
    array_push($data, $row->product_id);
    array_push($data, $row->product_name);
    array_push($data, $row->product_code);
    array_push($data, $row->text);

    fputcsv($file, $data);
}

fclose($file);

Example output is:

2131,"Toys set 35", TSSET35, "Lorem ipsum dolor sit amet"

I tried it with:

    preg_replace("/([a-z0-9]+)/i", '"$1"', $row->product_id)

    '"'.$row->product_id.'"'

With "preg_replace" I get some times more quotes then needed...

I need there quotes on all export items, how can I do that?

like image 890
Caner Avatar asked Jan 05 '23 06:01

Caner


1 Answers

Convert all data to string by strval function, then try to use fwrite instead of fputcsv:

function push(&$data, $item) {
    $quote = chr(34); // quote " character from ASCII table
    $data[] = $quote . addslashes(strval($item)) . $quote;
}

foreach ($data_for_export as $row) {
    $data = [];

    push($data, $row->product_id);
    push($data, $row->product_name);
    push($data, $row->product_code);
    push($data, $row->text);

    // separate array items by ',' and add the End-Of-Line character
    fwrite($file, implode(',', $data) . PHP_EOL); 
}

fclose($file);
like image 166
Mateusz Palichleb Avatar answered Jan 13 '23 09:01

Mateusz Palichleb