csv 不会忽略 ','(逗号)并使用 php 创建新行

csv does not ignore the ',' (comma) and makes a new row using php

我正在使用 php 从数据库下载 table 并将其保存为 .csv 文件。但是,当其中一列在字符串中包含逗号“,”时,脚本会将字符串的其余部分(在逗号之后)带到新列中。我怎样才能让脚本忽略那个逗号?

我试过在它旁边放一个“\”或使用 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 中正确加载(逐列、逐行)。

在任何人开始说你为什么这样做以及我这样做是为了练习之前。

将 $field_name 放在引号中以便被视为字符串就可以了!

if (preg_match('/\r|\n|,|"/', $field_name))
                {
                $field_name = '"'.$field_name.'"';
            //field_name = '' . str_replace(',','.', $field_name) . '';
            }

既然你在练习,这里有一些 csv 的基本规则(假设逗号作为分隔符):

123,test,456

当字段包含分隔符时,该字段必须用双引号引起来:

123,"monitor, Samsung","45,8"

换句话说,如果一个字段用双引号括起来并不意味着它是一个字符串,只是该字段内有(或可能有)分隔符。

当引用字段还包含引号时,必须用另一个引号将其转义:

123,"monitor 24"", Samsung","45,8"

当您自己进行解析时,记住这一点很重要。 (实际上,一旦你开始使用双引号,所有包含双引号的字段也应该被引用,即使里面没有分隔符)

多行字段也必须用双引号引起来:

123,"monitor 24"", Samsung","test multiline 
field","45,8"

以上其实是1行