★ wanayoo — archive 1999 http://fr.php.net/manual/fr/function.fgetcsv.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links 
search for in the  
previousfgetcfgetsnext
Last updated: Tue, 09 Jul 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Slovak | Spanish | Swedish | Turkish

fgetcsv

(PHP 3>= 3.0.8, PHP 4 )

fgetcsv --  Renvoie la ligne courante et cherche les champs CSV

Description

array fgetcsv ( resource fp, int length [, string delimiter])

Identique à fgets() mais fgetcsv() analyse la ligne qu'il lit et recherche les champs CSV, qu'il va retourner dans un tableau les contenant. Le délimiteur de champs delimiter est la virgule, à moins que vous ne fournissiez un troisième argument.

fp doit être un pointeur valide, et avoir été correctement ouvert par fopen(), popen(), ou fsockopen().

length doit être plus grand que la plus grande ligne trouvée dans un fichier CSV (en comptant les caractères de fin de ligne).

fgetcsv() retourne FALSE en cas d'erreur, ou en cas de fin du fichier.

Note : une ligne vide dans un fichier CSV sera retournée dans le tableau comme une chaîne vide, et ne sera pas traitée comme une erreur.

Exemple 1. Exemple avec fgetcsv()

<?php
  $row = 1;
  $fp = fopen ("test.csv","r");
  while ($data = fgetcsv ($fp, 1000, ",")) {
    $num = count ($data);
    print "<p> $num champs dans la ligne $row: <br>";
    $row++;
    for ($c=0; $c<$num; $c++) {
        print $data[$c] . "<br>";
    }
  }
  fclose ($fp);
?>
User Contributed Notes
fgetcsv
add a note about notes
rtreat2 at tampabay dot rr dot com
31-Mar-2001 12:17

by default, fgetcsv ignores commas in quoted fields. For example the following two rows would return the same number of fields (5):

3,thomas bros.,6,1998,good
3,"thomas, inc",6,1998,good

shoody at hotmail dot com
06-Jul-2001 01:05

For the MacIntosh-made file, try to couvert the "\r" by "\n" first, then use the fgetcsv. I know it can be slow for larger file, but i only find this way to do that myself. Nobody have best idea?
blair at squiz . net
15-Aug-2001 02:19

Here is a function that takes an array and adds a CSV line to the passed file pointer.

#-------------------------------------

function fputcsv ($fp, $array, $deliminator=",") {

$line = "";
foreach($array as $val) {
# remove any windows new lines,
# as they interfere with the parsing at the other end
$val = str_replace("\r\n", "\n", $val);

# if a deliminator char, a double quote char or a newline
# are in the field, add quotes
if(ereg("[$deliminator\"\n\r]", $val)) {
$val = '"'.str_replace('"', '""', $val).'"';
}#end if

$line .= $val.$deliminator;

}#end foreach

# strip the last deliminator
$line = substr($line, 0, (strlen($deliminator) * -1));
# add the newline
$line .= "\n";

# we don't care if the file pointer is invalid,
# let fputs take care of it
return fputs($fp, $line);

}#end fputcsv()


#-------------------------------------

mike dot schuh at gmx dot at
05-Mar-2002 01:17

Or just use
$line = fgets ($fp,1024);
to read one line (should be seperated by ; or , or .........) and then explode it
$part = explode (";",$line);

joeldegan-AT-yahoo.com
12-Jun-2002 08:01

// function to parse multi arrays into csv data
// array in... array of array(datasets); first dataset = field names.
// usage:
/*
$toparse[0][0] = "field1";
$toparse[0][1] = "field2";
$toparse[1][0] = "value1";
$toparse[1][1] = "123123123"; // to see
echo export_to_csv($toparse);
*/
function export_to_csv($inarray){
while (list ($key1, $val1) = each ($inarray)) {
while (list ($key, $val) = each ($val1)) {
if (is_numeric($val)){
$sendback .= $val.",";
}else{
$sendback .= "\"". $val ."\",";
}//fi
}//wend
$sendback = substr($sendback, 0, -1); //chop last ,
$sendback .= "\n";
}//wend
return ($sendback);
}// end function

// send the file to the client.. pretty simple.
//usage:send_file_to_client("data.csv",export_to_csv($data));

function send_file_to_client($filename, $data){
header("Content-type: application/ofx");
header("Content-Disposition: attachment; filename=$filename");
echo $data;
};

c dot greenNOSP at Mits dot uq dot edu dot au
24-Jun-2002 03:21

Quoting csv is pretty simple, and there are two steps..I note in previous comments only the second step has been explained.

First fields with double quotes need to double up the quotes, ie _He said "Timmy"..._ should become _He said ""Timmy""..._
Secondly as mentioned above, fields with commas need double quotes.

Here is a simple function to achieve this, that I pass to array walk, if you want to use it somewhere else, prob get rid of reference and return the value.

function check_csv_field_ref(&$item) {
$item = str_replace('"', '""', $item);
if (strpos($item, ",") !== FALSE) {
$item = '"' . $item . '"';
}
}

justin at indent dot com dot au
08-Aug-2002 07:24

If you're working in Excel on a Mac and are exporting a spreadsheet as a CSV, PHP won't recognise the line breaks, and interprets the file as one really long line. It borders on a bug really. For me, I just open the file in BBEdit or BBEdit Lite, convert the file from Mac to Unix, and all is well. But if you're dealing with user-contributed files, you'll need to convert the line-endings first... replacing all \r's with \n's should do it.
add a note about notes
previousfgetcfgetsnext
Last updated: Tue, 09 Jul 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Sun Oct 27 04:18:06 2002 CET