我正在使用以下代码下载 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 的列会受到干扰(我的意思是数据未低于适当的列标题)。可以用什么代替逗号来执行此代码?
最佳答案
不要手动创建 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);
}
关于php - mysql 到 csv 格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22689222/