This php function parses a CSV file and returns the data in a multidimensional array. I use it in many of my scripts and it works perfectly on all CSV files. So if you need a PHP CSV function that is simple and here for anyone to take, please use it.
I will post an example of its use later
Now I do not take credit for writing this function, I found it somewhere. I cannot remember where I did and would give the developer full credit if I knew.PHP Code:function importcsv($file, $head = false, $delim = ",", $len = 1000)
{
$return = false;
$handle = fopen($file, "r");
if ($head)
{
$header = fgetcsv($handle, $len, $delim);
}
while (($data = fgetcsv($handle, $len, $delim)) !== false)
{
if ($head and isset($header))
{
foreach ($header as $key => $heading)
{
$row[$heading] = (isset($data[$key])) ? $data[$key] : '';
}
$return[] = $row;
}
else
{
$return[] = $data;
}
}
fclose($handle);
return $return;
}
So let's say that your CSV file contents looked like this:
So to test this, you could write a simple foreach () loop after passing this function your CSV fileCode:"ID","USERNAME","LASTNAME" "00540000000wxjkAAA","heather@sportsrant.com","Simonds" "00540000000wvEyAAI","simonds@sportsrant.com","Simonds"
and your output would be something like this:PHP Code:$file = 'extract.csv';
$data = importcsv($file, $head = true);
foreach ($data as $line)
{
echo '<pre>' . print_r($line, true) . '</pre>';
}
exit;
Code:Array ( [ID] => 00540000000wxjkAAA [USERNAME] => heather@sportsrant.com [LASTNAME] => Simonds ) Array ( [ID] => 00540000000wvEyAAI [USERNAME] => simonds@sportsrant.com [LASTNAME] => Simonds )
This is really a great PHP snippet for parsing CSV files and extremely easy to use
Mike, I am just finishing up a project where I implemented a CSV importer that takes data from Eventbrite.com and imports it into custom objects in Salesforce. It's pretty slick and I used this function.
One important thing to note about it. It's not UTF-8 compliant. If you have double-byte characters in the data, it can cause problems. I Googled around for fixes and there were some suggestions about setting a locale and the like, but nothing worked.
It's a great function, but that's a caveat to it.
Yeah Scott I did notice that problem too when I was writing a series of scripts that process a system like you built kind of like that. I found a way around that though:
I am sure that you already know of the utf8_encode function, but I was getting API errors back from salesforce on some of my inserts and added this and the errors went awayPHP Code:foreach ($data as $key => $value)
{
$data[$key] = utf8_encode($value);
}
I am also going to email you a little script that may help you out
~Mike
Bookmarks