可能的重复:
将 MySQL 查询转换为 CSV 的 PHP 代码 < /p>
你好我正在从 mysql 记录生成一个 csv 文件,以“,”逗号分隔。我从数据库中获取数据并将其连接在一个字符串中。我正在使用以下代码
for($i=0;$i<count($all_logs);$i++)
{
$rd=$project->fetchRow($project->select()->where('id='.$all_logs[$i]->user2project_id));
$username=$userid->fetchRow($userid->select()->where('id='.$all_logs[$i]->user_id));
$outstr .=$all_logs[$i]->log_date.",";
$outstr .=$username->username.",";
$outstr .=$rd->title.",";
$outstr .=$all_logs[$i]->task.",";
$outstr .=$all_logs[$i]->workdesc.",";
$outstr .=$all_logs[$i]->hours.",";
$outstr .="\n";
}
return $outstr;
现在我的问题是什么。如果任何列数据本身带有“,”逗号,则它将将此 1 列拆分为 2 列。例如,如果我的列 workdesc
包含这样的数据 I work on this,that,these and those
那么它会将这 1 列放入生成的 csv 中的 3 列。任何人都可以告诉我如何摆脱这种情况......
Possible Duplicate:
PHP code to convert a MySQL query to CSV
Hi I am generating a csv file from mysql record seperated by "," comma. I fetch data from database and concate it in a string. I am using following code
for($i=0;$i<count($all_logs);$i++)
{
$rd=$project->fetchRow($project->select()->where('id='.$all_logs[$i]->user2project_id));
$username=$userid->fetchRow($userid->select()->where('id='.$all_logs[$i]->user_id));
$outstr .=$all_logs[$i]->log_date.",";
$outstr .=$username->username.",";
$outstr .=$rd->title.",";
$outstr .=$all_logs[$i]->task.",";
$outstr .=$all_logs[$i]->workdesc.",";
$outstr .=$all_logs[$i]->hours.",";
$outstr .="\n";
}
return $outstr;
Now what is my problem. If any column data is itself is having a " ," comma then it splits this 1 column to 2 columns. For example if my column workdesc
is having data like this I worked on this,that,these and those
then it will put this 1 column to 3 columns in generted csv. Any body can tell me how can I escape from this situation......
发布评论
评论(3)
为了构建 CSV 文件,不应使用字符串连接。
相反,您应该使用
fputcsv()
函数——如果您不想写入文件,而是获取字符串作为结果,请查看 用户 注释,您将在其中找到几种可能的解决方案;-)Using that function, you will not have to deal with escaping the enclosure nor delimiter yourself : all this will already be done for you.
In order to construct a CSV file, you should not use strings concatenations.
Instead, you should use the
fputcsv()
function -- and if you do not want to scrite to a file, but get a string as a result, take a look at the users notes, in which you'll find several possible solutions ;-)Using that function, you will not have to deal with escaping the enclosure nor delimiter yourself : all this will already be done for you.
您必须将值放在引号中,例如
在所有数据列上应用此格式,仅此而已。
You have to put values in quotes something like this
Apply this format on all the data columns and that's it.
如果列数据本身有逗号,那么你应该使用双引号来转义它。
例如,如果您的columndata =“some,data”;那么你的 csv 应该看起来像 -
所以最好为你的列数据加上双引号。
If the column data itself has comma, then you should use double quotes to escape it.
example if your columndata = "some,data"; then your csv should look like -
So better have double quotes enclosed for your column data.