Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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);
  }
}
?>

I took the solution from @Orangepill and refactored / simplified it in a couple of ways. This may also become handy if you want every field to be enclosed which is not the case in the default php implementation.

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");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top