Making CSV Files With PHP

Making CSV Files With PHP

Making CSV files with PHP can de done very effectively. You may want to make custom lists that users can download in the form of csv files. Then, the file can be opened in Excel and the report can be presented at the next meeting.

The code below demostrates two methods for which csv files can be created.

Method A

function get_csv($values) {
return implode(',', $values) . "\n";
}
 
$fh = fopen('mycsv.csv','wb');
 
$command = "SELECT * FROM tablename ";
$result = mysqli_query($db, $command);
 
while($row = mysqli_fetch_assoc($result)){
$id = trim($row['id']);
$name = trim($row['name']);
 
$get_csv = get_csv($row);
 
fwrite($fh, $get_csv);
}
 
fclose($fh);

Method B

$fp = fopen('myfile.csv', 'wb');
// get array from while loop
$command = "SELECT * FROM tablename ";
$result = mysqli_query($db, $command);
 
while($row = mysqli_fetch_assoc($result)){
$id = trim($row['id']);
$name = trim($row['name']);
 
$vars[] = $id.",".$name;
 
fwrite($fh, $get_csv);
}
 
foreach ($vars as $field) {
   // need to make array from $field string
   fputcsv($fp, explode(',',$field));
}
 
fclose($fp);