While writing my series on extracting data from Google Analytics emails with PHP I discovered PHP has a new function called str_getcsv which works the same way as fgetcsv but extracts CSV data from a string instead of from a file.
Unfortunately this is only available from PHP 5.3.0 (which has not yet been released) but the manual page for the function contains some useful examples of creating your own function to put the row into a memory "file" and then use the fgetcsv function to read from it. You still need PHP 5.1.0 for this to work.
While this won’t be as efficient as using the str_getcsv function it does provide a way to use this functionality in earlier versions of PHP.
Here’s the code:
if(!function_exists('str_getcsv')) { function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\") { $fp = fopen("php://memory", 'r+'); fputs($fp, $input); rewind($fp); $data = fgetcsv($fp, null, $delimiter, $enclosure); // $escape only got added in 5.3.0 fclose($fp); return $data; } }
I can’t take credit for this myself. It was posted on the str_getcsv manual page by "daniel dot oconnor at gmail dot com" and I’ve simply modified it to use php://memory instead of the way he does it.