我使用以下代码以csv格式下载mysql数据。
require_once("../database.php");
//Enter the headings of the excel columns
$contents="Database Id,Last Name,First Name,Middle Name,User Name,Email,Permanent Address,Communication Address,City,Zipcode,State,Country,Mobile,Birth Date,Gender,Council Number,College,Registering As,Selected,BAMS Year,Internship Place,PG Subject,PG Title,PHD Subject,PHD Title,Other As Student,Selected ,Practicing Since,Practitioner PG Subject,Practitioner PG Title,Practitioner PHD Subject,Practitioner PHD Title,Other As Practitioner,Clinic Address,Accommodation Selected,Payment Mode,Member Status,Password Changed,Form Submission Date,Registration Activation Date,Memebrship Expires On,Last Log In Date\n";
$user_query = mysql_query("SELECT * from tablename ORDER BY RAND()");
while($row = mysql_fetch_array($user_query))
{
$contents.=$row['reg_id'].",";
$contents.=$row['lname'].",";
$contents.=$row['fname'].",";
$contents.=$row['mname'].",";
$contents.=$row['username'].",";
$contents.=$row['email'].",";
$contents.=$row['address'].",";
$contents.=$row['comaddress'].",";
$contents.=$row['city'].",";
$contents.=$row['zipcode'].",";
$contents.=$row['state'].",";
$contents.=$row['country'].",";
$contents.=$row['mobile_num'].",";
$contents.=$row['birthdate'].",";
$contents.=$row['gender'].",";
$contents.=$row['council_num'].",";
$contents.=$row['college'].",";
$contents.=$row['education'].",";
$contents.=$row['extra'].",";
$contents.=$row['bamsyear'].",";
$contents.=$row['interneeplace'].",";
$contents.=$row['pgsubject'].",";
$contents.=$row['pgtitle'].",";
$contents.=$row['phdsubject'].",";
$contents.=$row['phdtitle'].",";
$contents.=$row['otherdetails1'].",";
$contents.=$row['practice'].",";
$contents.=$row['practicesince'].",";
$contents.=$row['pgsubjectp'].",";
$contents.=$row['pgtitlep'].",";
$contents.=$row['phdsubjectp'].",";
$contents.=$row['phdtitlep'].",";
$contents.=$row['otherdetails2'].",";
$contents.=$row['clinicaddress'].",";
$contents.=$row['accommodation'].",";
$contents.=$row['payment_mode'].",";
$contents.=$row['member_status'].",";
$contents.=$row['pwchng_flag'].",";
$contents.=$row['form_submission_date'].",";
$contents.=$row['registration_date'].",";
$contents.=$row['expiry_date'].",";
$contents.=$row['last_login_date'].",";
$contents.=$row['status']."\n";
}
// remove html and php tags etc.
$contents = strip_tags($contents);
//header to make force download the file
header("Content-Disposition: attachment; filename=my_members_".date('d-F-Y').".csv");
print $contents;
现在面临的问题是
CSV已下载,但数据未进入相应的列....
如果有人在数据字段中使用逗号,则csv会受到干扰列(我的意思是数据不会低于适当的列标题)。可以使用什么代替逗号来执行此代码?
答案 0 :(得分:1)
不要手动创建CSV,请使用现有的fputcsv
函数:
header("Content-Disposition: attachment; filename=my_members_".date('d-F-Y').".csv");
$out = fopen('php://output', 'w');
while ($row = mysql_fetch_assoc($user_query)) {
fputcsv($out, $row);
}