|
|
 |
fgetcsv (PHP 3>= 3.0.8, PHP 4 ) fgetcsv -- Gets line from file pointer and parse for CSV fields Descriptionarray 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 optional third delimiter
parameter defaults as a comma. The optional enclosure
cannot be null, and is limited to one character. If
enclosure is more than one character, only the
first character is used.
Note:
The enclosure parameter was added in PHP 4.3.0.
The fp parameter must be a valid file pointer to a file
successfully opened by fopen(),
popen(), or fsockopen().
The length parameter 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.
Note:
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.
Example 1. Read and print the entire contents of a CSV file <?php
$row = 1;
$fp = fopen ("test.csv","r");
while ($data = fgetcsv ($fp, 1000, ",")) {
$num = count ($data);
print "<p> $num fields in line $row: <br>\n";
$row++;
for ($c=0; $c < $num; $c++) {
print $data[$c] . "<br>\n";
}
}
fclose ($fp);
?> |
|
See also explode(), file(),
and pack()
User Contributed Notes fgetcsv |
 |
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.
|
|
martin dot goldinger at netserver dot ch
28-Oct-2002 01:12 |
|
With MAC, use: Save As - CSV for Windows. Then fgetcsv works as expected.
|
|
php at dogpoop dot cjb dot net
16-Nov-2002 03:01 |
|
This function takes a csv line and splits it into an array, much like
fgetcsv does but you can use it on data that isn't coming in from a file,
or you can read data from a file some other way (like if your Mac files
aren't being read correctly) and use this to split it. If you have any
corrections, comments (good or bad), etc. I would appreciate an email to
the above address.
function
csv_split($line,$delim=',',$removeQuotes=true) { #$line: the csv line
to be split #$delim: the delimiter to split by #$removeQuotes: if
this is false, the quotation marks won't be removed from the fields
$fields = array(); $fldCount = 0; $inQuotes = false;
for ($i = 0; $i < strlen($line); $i++) { if
(!isset($fields[$fldCount])) $fields[$fldCount] = "";
$tmp = substr($line,$i,strlen($delim)); if ($tmp === $delim
&& !$inQuotes) { $fldCount++; $i +=
strlen($delim)-1; } else if ($fields[$fldCount] == ""
&& $line[$i] == '"' && !$inQuotes) {
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = true; } else if ($line[$i] == '"') {
if ($line[$i+1] == '"') { $i++;
$fields[$fldCount] .= $line[$i]; } else {
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = false; } } else {
$fields[$fldCount] .= $line[$i]; } } return
$fields; }
|
|
 |
| |