替代fputcsv

时间:2013-06-05 14:25:16

标签: php fputcsv

我有一个数组,我想导出到CSV文件,现在我知道有一个fputcsv函数,但我使用的是PHP 5.0.4版本,所以这不适合我。

我可以使用替代方法吗?

3 个答案:

答案 0 :(得分:0)

您可以使用polyfill。编写你的代码,好像你在支持fputcsv的系统上的位置从php块中的注释(带有一些轻微的框架代码)但是包括这个 (从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);
  }
}
?>

答案 1 :(得分:0)

假设您有一个$Data数组,其中包含每个注册表(或行)的各个数组,您可以尝试这样做:

$Delimiter = '"';
$Separator = ','
foreach($Data as $Line)
{   
 fwrite($File, $Delimiter.
        implode($Delimiter.$Separator.$Delimiter, $Line).$Delimiter."\n");
}

$File是您文件的句柄。将$Delimiter,要放在每个字段周围的字符放在$Separator中,放在字段之间使用的字符。

答案 2 :(得分:0)

我从@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");
}