|
|
 |
fputcsv (PHP 5 >= 5.1.0RC1) fputcsv --
Formatea la lÃnea como CSV y la escribe en el archivo apuntado Descripciónint fputcsv ( resource handle [, array fields [, string delimiter [, string enclosure]]] )
fputcsv() da formato a lÃnea (pasada como matriz
en fields) como CSV y la escribe en el archivo
especificado por handle. Regresa la longitud de la
cadena escrita, o FALSE en caso de falla.
El parámetro opcional delimiter fija el
delimitador de campo (sólo un caracter). Por defecto es una coma:
,.
El parámetro opcional enclosure fija el
empaquetador del campo (sólo un caracter) y el valor por defecto
son las dobles comillas ".
Ejemplo 1. Ejemplo de 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);
?>
|
|
Nota: Si sufre problemas con
PHP no reconociendo los finales de lÃnea
cuando lee archivos creados en un Macintosh (o leyendo archivos sobre
uno), puede probar activando la opción de configuración
auto_detect_line_endings.
Vea también fgetcsv().
02-Aug-2006 05:09
It's unrealistic to require the field enclosure to be one character because it's very common to have "empty string" as the field delimiter (especially when TAB is used as field delimiter).
I tried to use "\0" as the field enclosure, hoping that'd be interpreted as an empty string, but fputcsv (in PHP5) translated it into literal.
By the way, fputcsv wrongly adds the field enclosures whenever a field contains a space. The expected behavior should be adding the field enclosures when a field contains a field delimiter.
heather at heathercash dot com
25-Sep-2005 04: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
15-Sep-2005 07: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)
{
$string = "";
$writeDelimiter = FALSE;
foreach($dataArray as $dataElement)
{
$dataElement=str_replace("\"", "\"\"", $dataElement);
if($writeDelimiter) $string .= $delimiter;
$string .= $enclosure . $dataElement . $enclosure;
$writeDelimiter = TRUE;
} $string .= "\n";
fwrite($filePointer,$string);
}
?>
twebb at boisecenter dot com
21-Jan-2005 05: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
22-Nov-2004 09: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
19-Nov-2004 09: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
11-Nov-2004 02: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)
| |
| | Citas célebres | No se puede separar la paz de la libertad, porque nadie puede estar en paz a menos que sea libre. Malcolm X Lider antirracista estadounidense (1925-1965) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Tiendas | | Vacío policial | - Perdone, ¿No ha visto cerca de aquí un policía?
- ¡Uy, hace como tres horas que no veo ni uno sólo!
- Pues entonces, ¡Arriba las manos! | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|