Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
The Electric Toolbox Blog
  • Linux
  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / PHP’s str_getcsv function

PHP’s str_getcsv function

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.

Check Out These Related posts:

  1. Using purge to free inactive memory on Mac OS X
  2. RFC 1321 – MD5 Message-Digest Algorithm
  3. Use PHP’s fputcsv without writing to a file
  4. Parsing Google Analytics data with PHP – CSV files
Categories PHP
Function to extract email attachments using PHP IMAP
Parsing Google Analytics data with PHP – CSV files

Categories

  • Apache
  • Applications
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Linux List Groups
  • Linux create user
  • How to Copy Directory Linux
  • Chmod 777 Tutorial
  • Add User To Group Linux
  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap
Copyright © 2025. Electric Tool Box. All Rights Reserved.