duanpai1033 2014-11-23 10:05
浏览 9
已采纳

如何使用PHP将csv头部的行括在双引号中?

if let's say I have

$headers = array(
"userid",
"fname",
"lname");

I want them to placed as header row (topmost part of the csv) separated by comma and enclosed each with double quotes.

I already tried

$fp = fopen('data.csv', 'w+'); 
fputcsv($fp,$headers,',','"');
fclose($fp);

they don't get enclosed with double quotes..how to do it?

  • 写回答

1条回答 默认 最新

  • dongqigu0429 2014-11-23 10:37
    关注

    You may try to force it like so:

    $headers = array(
        '"userid"',
        '"fname"',
        '"lname"'
    );
    

    By wrapping the values in actual quotes, and then just use a blank enclosure string:

    $fp = fopen('data.csv', 'w+'); 
    fputcsv($fp,$headers,',','');
    fclose($fp);
    

    To force it to exclude your quotes in the "needs to be enclosed" characters (PHP checks if the enclosure character is already inside the string, and escapes+encloses if necessary).

    However, in new versions of PHP, you will get this error:

    fputcsv(): enclosure must be a character
    

    In which case, I would just recommend doing it yourself, like so:

    function put_csv_headers($handle, $headers, $separator, $enclosure) {
        // [add some error checks here, of course]
        array_walk($headers, function(&$item, $i, $enc) {
            $item = $enc . $item . $enc; // wrap the header with the enclosure
        }, $enclosure);
        fputs($handle, implode($separator, $headers));
    }
    

    And:

    $headers = array('userid', 'fname', 'lname');
    $fp = fopen('data.csv', 'w+'); 
    put_csv_headers($fp, $headers, ',', '"');
    fclose($fp);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题