【发布时间】:2011-04-06 07:37:14
【问题描述】:
此代码创建一个 csv 文件。但是,我避免在字段中打印逗号,因为它被用作分隔符(参见第 22 行)。现在我想从字段中删除(回车和新行)。添加 $somecontent .= str_replace("\n", "", $val);第23行似乎不起作用。有什么想法吗?
@chmod($export_csv, 0777);
$fe = @fopen($export_csv."/export.csv", "w+");
if($fe){
$somecontent = "";
$fields_count = 0;
// print field headers
$db->query($sql_view);
if($row = $db->fetchAssoc()){
foreach($row as $key => $val){
if($fields_count++ > 0) $somecontent .= ",";
$somecontent .= ucfirst($key);
}
}
$somecontent .= "\n";
// print field values
$db->query($sql_view);
while($row = $db->fetchAssoc()){
$fields_count = 0;
foreach($row as $key => $val){
if($fields_count++ > 0) $somecontent .= ",";
$somecontent .= str_replace(",", "", $val);
$somecontent .= str_replace("\n", "", $val);
}
$somecontent .= "\n";
}
// write some content to the opened file.
if (fwrite($fe, $somecontent) == FALSE) echo 'file_writing_error'." (export.csv)";
fclose($fe);
}
【问题讨论】:
-
为什么不尝试使用 PHP 内置的 fputcsv() 函数呢?
-
感谢马克:现在阅读它。关于我所拥有的,你能给我一个先机吗?
标签: php csv export-to-csv