3

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->uid);
  $output .= $user->uid . ',' . $user->name . ',' . $user->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?

1 Answer 1

5

@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->uid);
  $output .= $user->uid . ',' . $user->name . ',' . $user->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

4
  • Still chinese though. Commented Aug 7, 2014 at 9:08
  • 1
    use ob_clean at the top of code Commented Aug 7, 2014 at 9:09
  • 1
    wait i am sending you code that i have used Commented Aug 7, 2014 at 9:10
  • 1
    Please check above updated code. Commented Aug 7, 2014 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.