Puneet Chawla Puneet Chawla - 5 months ago 62
MySQL Question

Concatenate static value while exporting CSV file using fputcsv in PHP

I am using below code to export CSV file using fputcsv in PHP. Code works proper and CSV file generates. All the values/records are coming from database. But I want to add dollar ($) symbol with some of column values.

Code for exporting CSV file.

$filename1 = "All Months.csv";
ob_end_clean();
$fp1 = fopen('php://output', 'w');

ob_start();
header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename='.$filename1);

fputcsv($fp1, array('Month', 'Year', 'Total Production', 'Credit Adjustments', 'Net Production', 'Hygiene Production', 'Collections', 'Account Receivable Total', 'New Patients', 'Break Even Points', 'Net Income', 'Hygiene %'));

$query = $db->query("SELECT Month, Year, Total_Production, Credit_Adjustments, Net_Production, Hygiene_Production, Collections, AC_Receivable_Total, New_Patients, Break_Even_Points, Net_Income, Hygiene FROM clientsdata WHERE Client_Id = '".$userID."'");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp1, $row);
}

exit();


Snapshot of exporting file -

enter image description here

Answer

If you want just to add $ sign you can do it this way:

while($row = $query->fetch(PDO::FETCH_ASSOC)) {
    $row['the_field_you_want'] = '$'.$row['the_field_you_want']
    fputcsv($fp1, $row);
}
Comments