Export data to CSV programmatically in drupal 7 I am using the following code to extract all the users belonging to a group:

// Send response headers to the browser.
drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment;filename=csvfiles.csv');

$output = '';
$keys = array(t('User id'), t('Username'), t('Email'));
if ($keys) {
  $output .= implode("\t", $keys) . "\n";
}
$members = _get_users_in_group($gid);
foreach ($members as $member) {
  $user = user_load($member-&gt;uid);
  $output .= $user-&gt;uid . ',' . $user-&gt;name . ',' . $user-&gt;mail . "\n";
}
print $output;
exit;
}


Even though I load all the users correctly the output I get is in Chinese. That means something is breaking the CSV format. Any ideas how to export data to CSV in Drupal 7?
@potney i have updated your code.Please check

drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment;filename=csvfiles.csv');

$output = '';
$keys = array(t('User id'), t('Username'), t('Email'));
if ($keys) {
  $output .= implode("\t", $keys) . "\n";
}
$members = _get_users_in_group($gid);
foreach ($members as $member) {
  $user = user_load($member-&gt;uid);
  $output .= $user-&gt;uid . ',' . $user-&gt;name . ',' . $user-&gt;mail . "\n";
}
ob_clean();
print $output;
exit;
}


I have used this code it works for me

            $filename='filename.csv';
            ob_clean();
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment;filename='.$filename);
            header('Cache-Control: max-age=0');

        $contents="Date  \n ";
$contents.='11/05/2014';

echo $contents;


Please check this.Hope this will work