Skip to content

Instantly share code, notes, and snippets.

@johanmeiring
Created June 8, 2012 08:52
Show Gist options
  • Save johanmeiring/2894568 to your computer and use it in GitHub Desktop.
Save johanmeiring/2894568 to your computer and use it in GitHub Desktop.
PHP str_putcsv function
<?php
/* From: http://www.php.net/manual/en/function.str-getcsv.php#88773 and http://www.php.net/manual/en/function.str-getcsv.php#91170 */
if(!function_exists('str_putcsv'))
{
function str_putcsv($input, $delimiter = ',', $enclosure = '"')
{
// Open a memory "file" for read/write...
$fp = fopen('php://temp', 'r+');
// ... write the $input array to the "file" using fputcsv()...
fputcsv($fp, $input, $delimiter, $enclosure);
// ... rewind the "file" so we can read what we just wrote...
rewind($fp);
// ... read the entire line into a variable...
$data = fread($fp, 1048576);
// ... close the "file"...
fclose($fp);
// ... and return the $data to the caller, with the trailing newline from fgets() removed.
return rtrim($data, "\n");
}
}
@mpyw
Copy link

mpyw commented Oct 2, 2015

Better implemention.

  • fread($fp, NUMBER_AS_LARGE_AS_YOU_CAN_THINK_OF) can be replaced stream_get_contents($fp).
<?php

if (!function_exists('str_putcsv')) {
    function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
        $fp = fopen('php://temp', 'r+b');
        fputcsv($fp, $input, $delimiter, $enclosure);
        rewind($fp);
        $data = rtrim(stream_get_contents($fp), "\n");
        fclose($fp);
        return $data;
    }
}

@piotr-cz
Copy link

piotr-cz commented Feb 23, 2017

Another way is to get resource size using ftell before rewind

$fpSize = ftell($fp);
rewind($fp);
$data = fread($fp, $fpSize);

@Richard87
Copy link

Also, I'm using $fp = fopen('php://memory', 'r+b');
To save the ammount of writing to disk :)

@BenceSzalai
Copy link

According to https://www.php.net/manual/en/wrappers.php.php even 'php://temp' should be in memory too as long as the contents are below a certain limit. Default is 2MiB. If you are not parsing huge arrays, 'php://temp' and 'php://memory' will do the same.

@lwcorp
Copy link

lwcorp commented Jul 12, 2023

Why was it tweaked from the original version, which had $data = fgets($fp);? And does anyone know why the original version got -1 points while it seems to work well?

@josefsabl
Copy link

josefsabl commented Nov 20, 2024

Why was it tweaked

I used the original and it is buggy. By using fgets it reads only one line from the stream. However csv supports linebreaks in cells.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment