note 17718 added to function.preg-split
| From: | williamNO_SPAM at ScriptingBizNoSpam dot Com | Date: | Thu, 20 Dec 2001 22:02:50 +0000 |
| Subject: | note 17718 added to function.preg-split | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-23466@lists.php.net to get a copy of this message | ||
Having trouble with CSV? (comma separated verbage)
I was, so I wrote this function. I've included 3
files here so you can make the three file, upload
them to the same directory, and view it from the web.
I started as a PERL hacker, which may explain things
that don't look like a typical php hacker.
-------------------------------------
csv.lib.php:
<?php
##############################################
function csv_to_array($line)
{
$l = preg_split("//",$line);
$field = 0; // initialize field counter
$q_open = 0; // initialize quote tracker
for($j=0; $j<count($l);$j++)
{
#-------------------------------#
if ($q_open == 0 && $l[$j] == ',')
{
$field++;
continue;
}
#-------------------------------#
if ($l[$j] == '"')
{
if ($q_open == 1){$q_open = 0;}else{$q_open = 1;}
continue;
}
#-------------------------------#
$fields[$field] .= $l[$j];
#print "$q_open - $field - $l[$j]<br>";
}
return $fields;
}
##############################################
?>
-------------------------------------
-------------------------------------
example.csv.php:
<?php
include("csv.lib.php");
// Open the file, and make an array of the rows
$lines = file("data.csv");
for($i=0; $i<count($lines);$i++)
{
if (! preg_match("/[a-zA-Z0-9,]/",$lines[$i]) ){
continue; // skip blank lines
}
print "$lines[$i]<br>\n";
$fields = csv_to_array($lines[$i]);
print " br br --BEGIN br ";
for($k=0; $k<count($fields); $k++)
{
print "$fields[$k]<br>";
}
print "--END br br br";
}
?>
-------------------------------------
-------------------------------------
data.csv:
"Praise God, this works!", 20011225, "Merry Christmas"
"Happy Thanksgiving!", 20011122, "Nov 22, 2001"
-------------------------------------
(This csv file should only have 2 lines,
so if there are extra line returns, be
sure to remove them :-), The manuel doesn't
allow for HTML tags, so change br to html and
add tabs and remove extra
line returns to make things legible)
--
http://www.php.net/manual/en/function.preg-split.php
http://master.php.net/manage/user-notes.php?action=edit+17718
http://master.php.net/manage/user-notes.php?action=delete+17718
http://master.php.net/manage/user-notes.php?action=reject+17718