dongzhui4927 2017-09-14 14:06
浏览 35
已采纳

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

I am downloading a table from a database using php and saving it as a .csv file. But when one of the columns contains a comma ',' inside the string the script takes the rest of the string (after the comma) to a new column. How can I make the script to ignore that comma?

I have tried putting a '\' next to it or using stripcslashes() but nothing works.

Part of the Code

$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('/\|\
|,|"/', $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 "
";
}
?>

EDIT:

If I don't use comma then the csv file won't load properly in excel (column by column, row by row).

Before anyone starts saying why you doing that and that I AM DOING IT FOR PRACTICE.

  • 写回答

2条回答 默认 最新

  • duannuan0074 2017-09-14 14:51
    关注

    puting the $field_name in quotes in order to be considered as a string will do the trick!!

    if (preg_match('/\|\
    |,|"/', $field_name))
                    {
                    $field_name = '"'.$field_name.'"';
                //field_name = '' . str_replace(',','.', $field_name) . '';
                }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题