note 63334 added to function.fgetcsv
| From: | theppg_001 at hotmail dot com | Date: | Mon, 20 Mar 2006 13:30:28 +0000 |
| Subject: | note 63334 added to function.fgetcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-106101@lists.php.net to get a copy of this message | ||
Hi there
I'm sure this isn't the best written code but it works for me and hopefully will help
others out
This function will convert CSV to an array.
It is setup to turn the first line into seperate arrays in the array.
(So the first line should be the header!)
Here is the code
<?php
function csv2array($source)
{
$sourceheader = substr($source,0,strpos($source, "\r\n"));
$sourceheader = str_replace('","', '";"', $sourceheader);
$sourceheader = substr($sourceheader,1);
$header = explode('";"',$sourceheader);
$source = substr($source,strpos($source, "\r\n"));
$source = '"'.$source;
$source = str_replace('","', '";"', $source);
$source = str_replace('", "', '";"', $source);
$source = str_replace('" ,"', '";"', $source);
$source = str_replace('" , "', '";"', $source);
$source = str_replace('"; "', '";"', $source);
$source = str_replace("\r\n", ";", $source);
$source = str_replace(",,", ";\"\";", $source);
$i = 0;
$imax = (count($header) -1);
$ii = 0;
while(substr($source,0,3) == '";"' AND strrpos($source,'";')
> 1)
{
if($i > $imax)
{
$i = 0;
$ii++;
}
$source = substr($source,3);
$endpos = strpos($source,'";"');
$token = substr($source,0,$endpos);
$array[$header[$i]][$ii] = $token;
$source = substr($source,strlen($token));
$i++;
}
return $array;
}
// Example usage
$csvdata = '"Name","Email","Phone","Comments"
"John Doe","Johndoe@hotmail.com","00 0000 0000", "this is an
example"
"Jane Doe","janedoe@yahoo.com","0000 000 000","This is another
example"';
$csvarray = csv2array($csvdata);
/* print_r ($csvarray) Returns
Array
(
[Name] => Array
(
[0] => John Doe
[1] => Jane Doe
)
[Email] => Array
(
[0] => Johndoe@hotmail.com
[1] => janedoe@yahoo.com
)
[Phone] => Array
(
[0] => 00 0000 0000
[1] => 0000 000 000
)
[Comments"] => Array
(
[0] => this is an example
)
) */
?>
----
Server IP: 203.220.0.234
Probable Submitter: 211.31.190.230
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.fgetcsv.php
Edit -- http://master.php.net/note/edit/63334
Del: integrated -- http://master.php.net/note/delete/63334/integrated
Del: useless -- http://master.php.net/note/delete/63334/useless
Del: bad code -- http://master.php.net/note/delete/63334/bad+code
Del: spam -- http://master.php.net/note/delete/63334/spam
Del: non-english -- http://master.php.net/note/delete/63334/non-english
Del: in docs -- http://master.php.net/note/delete/63334/in+docs
Del: other reasons-- http://master.php.net/note/delete/63334
Reject -- http://master.php.net/note/reject/63334
Search -- http://master.php.net/manage/user-notes.php