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 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题