fputcsv() add quotes to every entry?
Asked Answered
D

1

5

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?

Drislane answered 3/10, 2016 at 9:58 Comment(2)
Why are quotes on all items a requirement? CSV doesn't require it as such, which is why PHP isn't adding quotes to items that don't need it.Sawfish
@Sawfish it's customer requirement :(Drislane
K
14

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);
Keijo answered 3/10, 2016 at 10:46 Comment(3)
You might also need to escape any existing quotes in the $item variable.Exuviae
I forgot that, thanks for your attention. Code edited.Keijo
Here is the best solution solution: https://mcmap.net/q/1922630/-add-quotes-to-csv-export You can use fputcsv, but you have to configure the enclosure to blank. Than you add manually quotes where you want.Indigo

© 2022 - 2024 — McMap. All rights reserved.