How to export data to CSV file

In php to export data to CSV file we use fputcsv funciton.

Following is the example code to convert data to CSV file:
$headerArray = ['S.No', 'Title', 'Count'];
//Below is Example Data records. We can also use live database table records
$data = [
    ['1', 'Example 1', '100'],
    ['2', 'Example 2', '50'],
    ['3', 'Example 3', '64'],
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=report.csv');
$fp = fopen('php://output', 'w');
fputcsv($fp, $headerArray);
foreach ($data as $key => $row) {
    fputcsv($fp, $row);
echo ob_get_clean();