Alternative to fputcsv

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 11:13:12

问题


I have an array that I want to export to a CSV file, now I know that there is a fputcsv function but I am using version 5.0.4 of PHP so this isn't an option for me.

Is there an alternative method I can use?


回答1:


Assuming you have a $Data array, which contains individual arrays for each registry (or line), you may try this:

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

Where $File is the handle for your file. Put in $Delimiter, the character you want to put around each field, and in $Separator, the character to use between fields.




回答2:


You can use a polyfill for this. write your code as if you where on a system that supports fputcsv From comments within the php block (with some slight framing code) but include this (copied and slightly modified from 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);
  }
}
?>


来源:https://stackoverflow.com/questions/16942531/alternative-to-fputcsv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!