note 86880 added to function.fgetcsv
| From: | dot) | Date: | Fri, 07 Nov 2008 17:38:31 +0000 |
| Subject: | note 86880 added to function.fgetcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-146292@lists.php.net to get a copy of this message | ||
A lot of the other solutions forget about the escaping of commas and string delimitation. A simple
"explode" will not work on a true CSV line. Here's a simple function I am using to
parse CSV lines. Should get others started if they want to add more options to the function and/or
make it more complex:
<?php
function my_parse_csv_str($line) {
$info = array();
$ignore = FALSE;
$delimiter = ",";
$ci = "";
for($i=0;$i <= strlen($line);$i++) {
$c = $line[$i];
if(($c == $delimiter || $c == "") && !$ignore) {
$info[] = $ci;
$ci = "";
}
else if($c == '"') {
$ignore = !$ignore;
}
else {
$ci .= $c;
}
}
return $info;
}
?>
This will parse csv lines like:
Jim, Joe,"Mary, Sue, and Bill"
into:
<?php
array(
[0] => Jim,
[1] => Joe,
[2] => Mary, Sue, and Bill,
);
?>
instead of:
<?php
array(
[0] => Jim,
[1] => Joe,
[2] => Mary
[3] => Sue
[4] => and Bill
);
?>
----
Server IP: 208.69.120.35
Probable Submitter: 65.189.233.201
----
Manual Page -- http://www.php.net/manual/en/function.fgetcsv.php
Edit -- https://master.php.net/note/edit/86880
Del: integrated -- https://master.php.net/note/delete/86880/integrated
Del: useless -- https://master.php.net/note/delete/86880/useless
Del: bad code -- https://master.php.net/note/delete/86880/bad+code
Del: spam -- https://master.php.net/note/delete/86880/spam
Del: non-english -- https://master.php.net/note/delete/86880/non-english
Del: in docs -- https://master.php.net/note/delete/86880/in+docs
Del: other reasons-- https://master.php.net/note/delete/86880
Reject -- https://master.php.net/note/reject/86880
Search -- https://master.php.net/manage/user-notes.php