A complete example to write your records (rows) to a csv file using PHP4.
<?php
if (!function_exists('fputcsv'))
{
function fputcsv(&$handle, $fields = array(), $delimiter = ';', $enclosure = '"')
{
$str = '';
$escape_char = '\\';
foreach ($fields as $value)
{
if (strpos($value, $delimiter) !== false ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false)
{
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i=0;$i<$len;$i++)
{
if ($value[$i] == $escape_char)
$escaped = 1;
else if (!$escaped && $value[$i] == $enclosure)
$str2 .= $enclosure;
else
$escaped = 0;
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2.$delimiter;
}
else
$str .= $value.$delimiter;
}
$str = substr($str,0,-1);
$str .= "\n";
return fwrite($handle, $str);
}
}
function WriteCsv($fileName, $delimiter = ';', $records)
{
$result = array();
foreach($records as $key => $value)
$results[] = implode($delimiter, $value);
$fp = fopen($fileName, 'w');
foreach ($results as $result)
fputcsv($fp, split($delimiter, $result));
fclose($fp);
}
# =================== test ====================
define('CSV_SEPERATOR',';');
define('CSV_PATH','\\');
define('CSV_FILENAME','results.csv');
$records = array (array('aaa','bbb','ccc','dddd'),
array('123','456','789'),
array('"test1"', '"test2"', '"test3"')
);
$fileName = $_SERVER['DOCUMENT_ROOT'] . CSV_PATH . CSV_FILENAME;
WriteCsv ($fileName,';',$records);
echo '<a href="' . CSV_PATH . CSV_FILENAME . '" target="_blanc">CSV File</a>';
?>
fputcsv
(PHP 5 >= 5.1.0)
fputcsv — 行を CSV 形式にフォーマットし、ファイルポインタに書き込む
説明
int fputcsv
( resource $handle
, array $fields
[, string $delimiter
[, string $enclosure
]] )
fputcsv() は、行(fields 配列として渡されたもの)を CSV としてフォーマットし、それを handle で指定したファイルに書き込みます (いちばん最後に改行を追加します)。
パラメータ
- handle
-
ファイルポインタは、有効なファイルポインタである必要があり、 fopen() または fsockopen() で正常にオープンされた (そしてまだ fclose() でクローズされていない) ファイルを指している必要があります。
- fields
-
値の配列。
- delimiter
-
オプションの delimiter はフィールド区切り文字 (一文字だけ) を指定します。デフォルトはカンマ (,) です。
- enclosure
-
オプションの enclosure はフィールドを囲む文字 (一文字だけ) を指定します。デフォルトは二重引用符 (") です。
返り値
書き込んだ文字列の長さを返します。失敗した場合は FALSE を返します。
例
Example#1 fputcsv() の例
<?php
$list = array (
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('file.csv', 'w');
foreach ($list as $line) {
fputcsv($fp, split(',', $line));
}
fclose($fp);
?>
注意
注意: マッキントッシュコンピュータ上で作成されたファイルを読み込む際に、 PHP が行末を認識できないという問題が発生した場合、 実行時の設定オプションauto_detect_line_endings を有効にする必要が生じるかもしれません。
fputcsv
boefje at hotmail dot com
10-Dec-2007 09:28
10-Dec-2007 09:28
hhheng at hkhangfong dot com
22-Nov-2007 04:51
22-Nov-2007 04:51
When I use the function above to write my data into a csv file, it will write all in one column. Actually I want to write in several columns like:
A B C C
1 2 3 4
How to to this? And how to output a specified cells? Like I want to start write from line 9, and column B.
ifunk
17-Sep-2007 10:04
17-Sep-2007 10:04
I converted this from the PHP source code. This replicates PHP5 functionality exactly, whereas the other examples here do not.
<?php
if (!function_exists('fputcsv')) {
function fputcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {
$str = '';
$escape_char = '\\';
foreach ($fields as $value) {
if (strpos($value, $delimiter) !== false ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i=0;$i<$len;$i++) {
if ($value[$i] == $escape_char) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2.$delimiter;
} else {
$str .= $value.$delimiter;
}
}
$str = substr($str,0,-1);
$str .= "\n";
return fwrite($handle, $str);
}
}
?>
alexxed thething gmail thething com
10-Aug-2007 04:28
10-Aug-2007 04:28
A event simpler way:
function fputcsv($hFile, $aRow, $sSeparator=',', $sEnclosure='"')
{
foreach ($aRow as $iIdx=>$sCell)
$aRow[$iIdx] = str_replace($sEnclosure, $sEnclosure.$sEnclosure, $sCell);
fwrite($hFile, join($aRow, $sSeparator)."\n");
}
Jonathon Hibbard at phpingenuity.com
04-Aug-2007 12:23
04-Aug-2007 12:23
This function is a replacement for PHP 4. It basically takes an array you pass it, and creates a delimited string. If you want ot use the key as the field name, you can tell the second paramater to use the key. The last is the delimiter you want each value to be seperated by. Should be pretty straight forward.
<?php
function generate_csv_data($data,$use_key=false,$delm=',') {
$output = NULL;
if(is_array($data)) {
if($use_key == false) {
if(isset($data[0]) && is_array($data[0])) {
foreach($data as $key) {
$output .= implode($delm,$key);
$output .= "\n";
}
} else {
$output .= implode("$delm", $data)."\n";
}
} else {
foreach($data as $key => $value) {
$output .= "$key{$delm}$value\n";
}
}
} else {
$output = $data;
}
if(empty($output)) {
trigger_error('OUTPUT WAS EMPTY!', E_USER_ERROR);
return false;
}
return $output;
}
?>
enzo dot d dot a at example dot com
26-Jun-2007 07:08
26-Jun-2007 07:08
Compact fputcsv function(), for Php version >= 4.0.5 and < 5.1.
Not a "good programming practice", but if you need save bytes ...
function fputcsv($fp, $arr, $del=",", $enc="\"") {
fwrite($fp, (count($arr)) ? $enc . implode("{$enc}{$del}{$enc}", str_replace("\"", "\"\"", $arr)) . $enc . "\n" : "\n");
}
bl at mindbench dot nl
26-Mar-2007 05:55
26-Mar-2007 05:55
If you need to save the output to a variable (e.g. for use within a framework) you can write to a temporary memory-wrapper and retrieve it's contents:
<?php
// output up to 5MB is kept in memory, if it becomes bigger it will automatically be written to a temporary file
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
fputcsv($csv, array('blah','blah'));
rewind($csv);
// put it all in a variable
$output = stream_get_contents($csv);
?>
MagicalTux at ooKoo dot org
18-Jan-2007 11:08
18-Jan-2007 11:08
If you need to send a CSV file directly to the browser, without writing in an external file, you can open the output and use fputcsv on it..
<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>
heather at heathercash dot com
26-Sep-2005 08:18
26-Sep-2005 08:18
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);
}
boonerunner at hotmail dot com
16-Sep-2005 11:47
16-Sep-2005 11:47
Here is an adaption of the above code that adds support for double quotes inside a field. (One double quote is replaced with a pair of double quotes per the CSV format).
<?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 = "";
// 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);
}
?>
twebb at boisecenter dot com
21-Jan-2005 10:54
21-Jan-2005 10:54
What about cells that span multiple lines? This function allows for cells to contain newlines:
function fputcsv($handle, $row, $fd=',', $quot='"')
{
$str='';
foreach ($row as $cell)
{
$cell = str_replace($quot, $quot.$quot, $cell);
if (strchr($cell, $fd) !== FALSE || strchr($cell, $quot) !== FALSE || strchr($cell, "\n") !== FALSE)
{
$str .= $quot.$cell.$quot.$fd;
}
else
{
$str .= $cell.$fd;
}
}
fputs($handle, substr($str, 0, -1)."\n");
return strlen($str);
}
I found this reference on the web:
http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm
drew at zitnay dot com
23-Nov-2004 02:42
23-Nov-2004 02:42
I found the following problems with the below function:
- when calling str_replace(), you must assign $cell the return value or nothing gets saved
- when using strchr(), you should explicitly check !== FALSE, or it'll treat a return value of 0 (found the character at string position 0) as FALSE
- Excel seems to quote not only fields containing commas, but fields containing quotes as well, so I've added another strchr() for quotes; I'm not saying Microsoft knows the correct way for sure, but it seems reasonable to me
- the original function put a space after each comma; that might be legal, I don't know, but I've never seen it (and I don't think it is, because then how would you indicate you wanted a field to start with a space other than by quoting it?)
- the original function didn't correctly return the length of the data outputted
Here's the function, fixed up a bit:
function fputcsv($handle, $row, $fd=',', $quot='"')
{
$str='';
foreach ($row as $cell) {
$cell=str_replace(Array($quot, "\n"),
Array($quot.$quot, ''),
$cell);
if (strchr($cell, $fd)!==FALSE || strchr($cell, $quot)!==FALSE) {
$str.=$quot.$cell.$quot.$fd;
} else {
$str.=$cell.$fd;
}
}
fputs($handle, substr($str, 0, -1)."\n");
return strlen($str);
}
Drew
arthur.at.korn.ch
20-Nov-2004 02:56
20-Nov-2004 02:56
The function in the prior comment doesn't escape quotes in fields, here mine:
function fputcsv($handle, $row, $fd=',', $quot='"')
{
$str='';
foreach ($row as $cell) {
str_replace(Array($quot, "\n"),
Array($quot.$quot, ''),
$cell);
if (strchr($cell, $fd)) {
$str.=$quot.$cell.$quot.$fd.' ';
} else {
$str.=$cell.$fd.' ';
}
}
fputs($handle, substr($str, 0, -2)."\n");
return $str-1;
}
arthur at mclean dot ws
12-Nov-2004 07:10
12-Nov-2004 07:10
Here's a simplistic fputcsv function that you can use until the real one gets out of CVS:
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 = "";
$writeDelimiter = FALSE;
foreach($dataArray as $dataElement){
if($writeDelimiter) $string .= $delimiter;
$string .= $enclosure . $dataElement . $enclosure;
$writeDelimiter = TRUE;
} // end foreach($dataArray as $dataElement)
// Append new line
$string .= "\n";
// Write the string to the file
fwrite($filePointer, $string);
} // end function fputcsv($filePointer, $dataArray, $delimiter)