Is there a way to access a string as a filehandle in php?

Erik picture Erik · Feb 16, 2010 · Viewed 8.8k times · Source

I'm on a server where I'm limited to PHP 5.2.6 which means str_getcsv is not available to me. I'm using, instead fgetcsv which requires "A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()." to operate on.

My question is this: is there a way to access a string as a file handle?

My other option is to write the string out to a text file and then access it via fopen() and then use fgetcsv, but I'm hoping there's a way to do this directly, like in perl.

Answer

Pascal MARTIN picture Pascal MARTIN · Feb 16, 2010

If you take a look in the user notes on the manual page for str_getcsv, you'll find this note from daniel, which proposes this function (quoting) :

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
        $fiveMBs = 5 * 1024 * 1024;
        $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
        fputs($fp, $input);
        rewind($fp);

        $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

        fclose($fp);
        return $data;
    }
}
?>

It seems to be doing exactly what you asked for : it uses a stream, which points to a temporary filehandle in memory, to use fgetcsv on it.


See PHP input/output streams for the documentation about, amongst others, the php://temp stream wrapper.


Of course, you should test that it works OK for you -- but, at least, this should give you an idea of how to achieve this ;-)