我正在使用php从数据库中下载表并将其保存为.csv文件。但是当其中一个列在字符串中包含逗号“,”时,脚本会将字符串的其余部分(逗号后面)带到新列中。我怎样才能让脚本忽略这个逗号?csv不会忽略','(逗号),并使用php创建一个新的行
我试过在旁边放一个'\'或使用stripcslashes(),但没有任何效果。
部分代码的
$rows = mysqli_fetch_assoc($select_table);
if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysqli_fetch_assoc($select_table);
}
// get total number of fields present in the database
function getcsv($no_of_field_names){
$separate = '';
// do the action for all field names as field name
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\\r|\\n|,|"/', $field_name))
{
$field_name = '' . str_replace(',','!', $field_name) . '';
}
echo str_replace('!',',', $field_name) . $separate . $field_name;
//sepearte with the comma
$separate = ',';
}
//make new row and line
echo "\r\n";
}
?>
编辑:
如果我不使用逗号,然后CSV文件将无法正常在Excel加载(逐列,行通过行)。
在任何人开始说你为什么要这样做,而我正在做它的实践。
你为什么要写出你自己的CSV解析器?改用[fputcsv](http://php.net/manual/en/function.fputcsv.php)。该页面的第一条评论是关于将其写入浏览器的。这将创建一个格式正确的CSV字符串。 – aynber
练习的人!实践!!!! – noel293
heh。好的,我会给你的。那么你想要做的是,如果该值包含逗号,请在该值附近加引号。这将告诉任何CSV解析器,该字符串内部的字符串不应该被分割,直到它碰到下一个引号。 – aynber