I'm trying to create a CSV from an array with some data and another array in it.
Code:
public function exportCSV()
{
$user = Auth::user();
$company = $user->company;
$dealers = $company->dealers;
$formatted_dealers = [];
foreach ($dealers as $dealer) {
if($dealer->is_deleted == 0){
array_push($formatted_dealers, $dealer);
}
}
if(count($formatted_dealers) > 0){
$csvData = array('name,phone,email,is_active,streetname,number,zip,city,special_id,products');
foreach($formatted_dealers as $dealer){
$products = [];
foreach ($dealer->products as $product) {
array_push($products, $product->slug);
}
$products = json_encode($products);
$csvData[] = $dealer->name . ',' . $dealer->phone . ',' . $dealer->email . ',' . $dealer->is_active . ',' . $dealer->address->streetname . ',' . $dealer->address->number . ',' . $dealer->address->zip . ',' . $dealer->address->city . ',' . $dealer->special_id . ',' . $products;
}
$new_time = date('d-m-Y h:i:s', strtotime('+2 hours'));
$filename = $new_time . '.csv';
$file_path = base_path() . '/' . $filename;
$file = fopen($file_path,'w+');
foreach ($csvData as $exp_data){
fputcsv($file, explode(',', $exp_data));
}
fclose($file);
$headers = ['Content-Type' => 'application/csv'];
return response()->download($file_path, $filename, $headers)->deleteFileAfterSend(true);
} else {
return redirect()->route('dealers.index', ['export' => 'error']);
}
}
So, I have some data, like the dealers name, phone etc. and an array of products that the dealer has. My line of thought was to json_encode the products array and then append to the string that is being pushed to the csvData array. But the result I'm getting when doing this is:
name,phone,email,is_active,streetname,number,zip,city,special_id,products
"Some name",11111111,example@example.com,1,xxxx,x,xxxx,xxxxxxxx,96548,"[""nBuGbW""","""qP3DAF""]"
"Another name",22222222,anoter@example.com,0,xxxxxxxx,x,xxxx,xxxxxx,,"[""nBuGbW""","""IRTQBN""]"
the products json array has way too many " and I can't seem to figure out why. Any ideas?
In my head it should be something like:
name,phone,email,is_active,streetname,number,zip,city,special_id,products
"Some name",11111111,example@example.com,1,xxxx,x,xxxx,xxxxxxxx,96548,["nBuGbW","qP3DAF"]"
"Another name",22222222,anoter@example.com,0,xxxxxxxx,x,xxxx,xxxxxx,,["nBuGbW","IRTQBN"]"