Forcing fputcsv to Use Enclosure For *all* Fields

后端 未结 5 1926
星月不相逢
星月不相逢 2020-11-29 11:44

When I use fputcsv to write out a line to an open file handle, PHP will add an enclosing character to any column that it believes needs it, but will leave other columns with

5条回答
  •  眼角桃花
    2020-11-29 12:42

    After a lot of scrafffing around and some somewhat tedious character checking, I have a version of the above referenced codes by Diego and Mahn that will correctly strip out encasings and replace with double quotes on all fields in fputcsv. and then output the file to the browser to download.

    I also had a secondary issue of not being able to be sure that double quotes were always / never escaped.

    Specifically for when outputting directly to browser using the php://input stream as referenced by Diego. Chr(127) is a space character so the CSV file has a few more spaces than otherwise but I believe this sidesteps the issue of chr(0) NULL characters in UTF-8.

    /***
     * @param $value array
     * @return string array values enclosed in quotes every time.
     */
    function encodeFunc($value) {
        ///remove any ESCAPED double quotes within string.
        $value = str_replace('\\"','"',$value);
        //then force escape these same double quotes And Any UNESCAPED Ones.
        $value = str_replace('"','\"',$value);
        //force wrap value in quotes and return
        return '"'.$value.'"';
    }
    
    
    $result = $array_Set_Of_DataBase_Results;
    $fp = fopen('php://output', 'w');
    if ($fp && $result) {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="export-'.date("d-m-Y").'.csv"');
        foreach($result as $row) {
            fputcsv($fp, array_map("encodeFunc", $row), ',', chr(127));
        }
        unset($result,$row);
        die;
    }
    

    I hope this is useful for some one.

提交回复
热议问题