导出到 csv,其中包含逗号的字符串,将其拆分
此代码将数据导出到 csv 文件中,该文件在 Excel 中打开。
当字符串中包含逗号时,它会打乱数据的顺序。
我需要帮助修改下面的代码来解析其中包含逗号的任何字符串,直到该字符串之后才创建新列。
我假设它将传递双引号内的每个字符串或包含该字符串的内容,因此这些引号内的任何逗号都会例外。
任何帮助表示赞赏。
$result = mysql_query("select lname, fname, email, dtelephone, etelephone, contactwhen, comments, thursday,
friday, saturday, sunday, monday FROM volunteers_2010");
$csv_output .= "Last Name,First Name,Email,Telephone (Day),Telephone (Evening),Contact When,Comments,Thursday,Friday,Saturday,Sunday,Monday,Comments\n";
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT lname, fname, email, dtelephone, etelephone, contactwhen, comments, thursday,
friday, saturday, sunday, monday FROM volunteers_2010 WHERE venue_id = $venue_id");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
This code exports data into a csv file, which is opened within Excel.
When a string has a comma within it, it messes up the order of the data.
I need help modifying my code below to resolve any strings that contain a comma within it, to not to create a new column until after the string.
I am assuming it will pass each string within double quotes or something that contains the string, so any comma within those quotes, then it will make an exception.
Any help is appreciated.
$result = mysql_query("select lname, fname, email, dtelephone, etelephone, contactwhen, comments, thursday,
friday, saturday, sunday, monday FROM volunteers_2010");
$csv_output .= "Last Name,First Name,Email,Telephone (Day),Telephone (Evening),Contact When,Comments,Thursday,Friday,Saturday,Sunday,Monday,Comments\n";
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT lname, fname, email, dtelephone, etelephone, contactwhen, comments, thursday,
friday, saturday, sunday, monday FROM volunteers_2010 WHERE venue_id = $venue_id");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看维基百科中的文章
嵌入逗号的字段必须用双引号字符括起来
see article in wikipedia
Fields with embedded commas must be enclosed within double-quote characters
fputcsv()
fputcsv()
正确格式:“test”、“test”、“在内部使用双引号”
第一个循环:
第二个循环:
Correct format: "test", "test,", "use double "" quotes inside"
1st loop:
2nd loop: