note 57164 modified in function.fputcsv by danbrown

From: Date: Thu, 20 Nov 2008 14:40:56 +0000
Subject: note 57164 modified in function.fputcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146753@lists.php.net to get a copy of this message
Here is an adaptation to boonerunner's function for fputcsv. It uses a 2-dimensional array. Each sub-array is a line in the csv file which then ends up being seperated by commas. <?php 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 = ""; // for each array element, which represents a line in the csv file... foreach($dataArray as $line){ // No leading delimiter $writeDelimiter = FALSE; foreach($line 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; } // Append new line $string .= "\n"; } // end foreach($dataArray as $line) // Write the string to the file fwrite($filePointer,$string); } ?> --was-- Here is an adaptation to boonerunner's function for fputcsv. It uses a 2-dimensional array. Each sub-array is a line in the csv file which then ends up being seperated by commas. 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 = ""; // for each array element, which represents a line in the csv file... foreach($dataArray as $line){ // No leading delimiter $writeDelimiter = FALSE; foreach($line 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; } // Append new line $string .= "\n"; } // end foreach($dataArray as $line) // Write the string to the file fwrite($filePointer,$string); } http://php.net/manual/en/function.fputcsv.php

« previous php.notes (#146753) next »