★ wanayoo — archive 1999 http://www.php.net/manual/zh/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: Sat, 17 Aug 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Czech | Dutch | Finnish | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

fgetcsv

(PHP 3>= 3.0.8, PHP 4 )

fgetcsv -- Gets line from file pointer and parse for CSV fields

Description

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

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. The field delimiter is a comma, unless you specify another delimiter with the optional third parameter. The enclosure character is double quote, unless it is specified. Delimiter and enclosure cannot be null and only first character is used when they are specified.

Fp must be a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()

Length must be greater than the longest line to be found in the CSV file (allowing for trailing line-end characters).

fgetcsv() returns FALSE on error, including end of file.

×¢: A blank line in a CSV file will be returned as an array comprising a single NULL field, and will not be treated as an error.

enclosure is added from PHP 4.3.0.

Àý×Ó 1. fgetcsv() example - Read and print entire contents of a CSV file

$row = 1;
$fp = fopen ("test.csv","r");
while ($data = fgetcsv ($fp, 1000, ",")) {
    $num = count ($data);
    print "<p> $num fields in line $row: <br>";
    $row++;
    for ($c=0; $c < $num; $c++) {
        print $data[$c] . "<br>";
    }
}
fclose ($fp);
User Contributed Notes
fgetcsv
add a note about notes
poc@baden-online.de
04-Apr-2000 07:36

fgetcsv() seems to ignore zero-length fields when working with tabs as separators (3.0.12).
Instead work around this with fgets() and do an explode() afterwards, this gets you the right thing.

fixed for php 4.0.4

ken@rets.net
14-Mar-2001 04:57

Following is a hack solution for those that do not have the latest and greatest...

If you have a better solution for those of us that do not/cannot use fgetcsv(), please post here!

BTW, if you view the souce of this page you can copy/paste the pretty version of this code. You'll need to remove the BRs tho.

Enjoy!

-Ken

########################################
function csv_parse ($data, $separator) {
$quote = '"';
$values = array();
$toggle = 0;
$len = strlen($data);
$count = 1;
for ($i = 0; $i < $len; $i++) {
$tmp = substr ($data, $i, 1);
if (strcmp($tmp, $quote) == 0) {
$toggle = $toggle ^ 1;
}
$value = $value . $tmp;
if (strcmp($tmp, $separator) == 0) {
if (! $toggle) {
# End of word
$value = ereg_replace(",$", "", $value);
$value = ereg_replace("^\"", "", $value);
$value = ereg_replace("\"$", "", $value);
$value = ereg_replace("\"+", "\"", $value);
$num_of_elems = count($values);
$values[$num_of_elems] = $value;
$value = "";
}
}
}
$value = ereg_replace("^\"", "", $value);
$value = ereg_replace("\"$", "", $value);
$value = ereg_replace("\"+", "\"", $value);
$num_of_elems = count($values);
$values[$num_of_elems] = $value;
return ($values);
}

rtreat2@tampabay.rr.com
30-Mar-2001 04: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@hotmail.com
05-Jul-2001 06: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?
pknutsen@nethut.noSPAM
18-Jul-2001 05:20

If you get an error message like "Wrong parameter count", drop the delimiter parameter (not supported in versions prior to PHP 4). fgetcsv() in these cases will only support the comma delimiter.

If you cannot predict the environment your script will work in, consider using comma delimiters whenever possible.

blair at squiz . net
14-Aug-2001 07: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.schuh@gmx.at
05-Mar-2002 06: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 01: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.greenNOSP@Mits.uq.edu.au
23-Jun-2002 08: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 . '"';
}
}

user4@example.com
02-Jul-2002 09:47

Does anybody knows how to delete blank lines at the end of a file?
justin at indent dot com dot au
08-Aug-2002 12: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: Sat, 17 Aug 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by: Web Hosting Talk
Last updated: Sun Aug 18 14:57:16 2002 EDT