我正要问与此处讨论的问题相同的问题.... 强制fputcsv使用Enclosure for*all*Fields
问题是
当我使用fputcsv写一行到打开的文件句柄时,PHP会将一个封闭的字符添加到它认为需要的任何列,但是会留下没有这些外壳的其他列.
例如,您最终可能会得到这样的一行
11,"Bob",Jenkins,"200 main st.USA"等
如果没有将虚假空间附加到每个字段的末尾,是否有任何方法可以强制fputcsv始终用外壳包含列(默认为")"字符?
答案是:
不,fputcsv()仅在以下条件下包含该字段
/* enclose a field that contains a delimiter, an enclosure character, or a newline */
if (FPUTCSV_FLD_CHK(delimiter) ||
FPUTCSV_FLD_CHK(enclosure) ||
FPUTCSV_FLD_CHK(escape_char) ||
FPUTCSV_FLD_CHK('\n') ||
FPUTCSV_FLD_CHK('\r') ||
FPUTCSV_FLD_CHK('\t') ||
FPUTCSV_FLD_CHK(' ')
)
Run Code Online (Sandbox Code Playgroud)
没有"永远封闭"选项.
我需要创建一个CSV文件将每个字段封闭...什么是最好的解决方案?
提前致谢...
滚动你自己的功能 - 不难:
function dumbcsv($file_handle, $data_array, $enclosure, $field_sep, $record_sep)
{
dumbescape(false, $enclosure);
$data_array=array_map('dumbescape',$data_array);
return fputs($file_handle,
$enclosure
. implode($enclosure . $field_sep . $enclosure, $data_array)
. $enclosure . $record_sep);
}
function dumbescape($in, $enclosure=false)
{
static $enc;
if ($enclosure===false) {
return str_replace($enc, '\\' . $enc, $in);
}
$enc=$enclosure;
}
Run Code Online (Sandbox Code Playgroud)
(上面是使用unix样式转义)
C.