note 63334 deleted from function.fgetcsv by nlopess
| From: | nlopess@php.net | Date: | Mon, 20 Mar 2006 22:01:05 +0000 |
| Subject: | note 63334 deleted from function.fgetcsv by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-106124@lists.php.net to get a copy of this message | ||
Note Submitter: theppg_001 at hotmail dot com
----
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
)
) */
?>