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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With