我有一个要导出到CSV文件的数组,现在我知道有一个fputcsv函数,但我使用的是PHP 5.0.4版本,所以这不是我的选择。
有没有其他方法可以让我使用?
发布于 2013-06-05 22:39:05
假设您有一个$Data数组,其中包含每个注册表(或行)的单独数组,您可以尝试这样做:
$Delimiter = '"';
$Separator = ','
foreach($Data as $Line)
{
fwrite($File, $Delimiter.
implode($Delimiter.$Separator.$Delimiter, $Line).$Delimiter."\n");
}其中$File是文件的句柄。在$Delimiter中,放入要放在每个字段周围的字符;在$Separator中,放入要在字段之间使用的字符。
发布于 2013-06-05 22:31:22
您可以使用polyfill来完成此操作。编写你的代码,就像你在一个支持fputcsv的系统上一样(带有一些轻微的框架代码),但要包含这个(从http://www.php.net/manual/en/function.fputcsv.php#56827复制并略微修改)
<?php
if (!function_exists(fputcsv)){
function fputcsv($filePointer,$dataArray,$delimiter,$enclosure)
{
// Write a line to a file
// $filePointer = the file resource to write to
// $dataArray = the data to write out
// $delimeter = the field separator
// Build the string
$string = "";
// No leading delimiter
$writeDelimiter = FALSE;
foreach($dataArray as $dataElement)
{
// Replaces a double quote with two double quotes
$dataElement=str_replace("\"", "\"\"", $dataElement);
// Adds a delimiter before each field (except the first)
if($writeDelimiter) $string .= $delimiter;
// Encloses each field with $enclosure and adds it to the string
$string .= $enclosure . $dataElement . $enclosure;
// Delimiters are used every time except the first.
$writeDelimiter = TRUE;
} // end foreach($dataArray as $dataElement)
// Append new line
$string .= "\n";
// Write the string to the file
fwrite($filePointer,$string);
}
}
?>发布于 2021-03-18 06:16:58
我从@Orangepill那里获得了解决方案,并通过几种方式对其进行了重构/简化。如果你想把每个字段都封闭起来,这也会很方便,这在默认的php实现中不是这样的。
function fputcsv_custom($handle, $fields, $delimiter = ",", $enclosure = '"', $escape_char = "\\") {
$field_arr = [];
foreach($fields as $field) {
$field_arr[] = $enclosure . str_replace($enclosure, $escape_char . $enclosure, $field) . $enclosure;
}
fwrite($handle, implode($delimiter, $field_arr) . "\n");
}https://stackoverflow.com/questions/16942531
复制相似问题