Skip to content

Commit

Permalink
Add function str_putcsv
Browse files Browse the repository at this point in the history
  • Loading branch information
lippserd committed Jan 17, 2019
1 parent 429c0a0 commit 85baa45
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,47 @@ function arrayval($subject)
get_php_type($subject)
));
}

/**
* Format the given input array as CSV string and return it
*
* The input array is always expected to be an array of rows.
* The keys of the first row will be automatically used as the header row.
*
* @param iterable $data
* @param string $delimiter Field delimiter
* @param string $enclosure Field enclosure
* @param string $escape Escape character
*
* @return string
*
* @throws \InvalidArgumentException
*/
function str_putcsv($data, $delimiter = ',', $enclosure = '"', $escape = '\\')
{
$fp = fopen('php://temp', 'r+b');

if (! is_iterable($data)) {
throw new \InvalidArgumentException(sprintf(
'str_putcsv expects arrays or instances of Traversable. Got %s instead.',
get_php_type($data)
));
}

foreach ($data as $row) {
fputcsv($fp, array_keys(arrayval($row)), $delimiter, $enclosure, $escape);

break;
}

foreach ($data as $row) {
fputcsv($fp, arrayval($row), $delimiter, $enclosure, $escape);
}

rewind($fp);
$csv = stream_get_contents($fp);
fclose($fp);
$csv = rtrim($csv, "\n"); // fputcsv adds a newline

return $csv;
}
27 changes: 27 additions & 0 deletions tests/php/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,31 @@ public function testArrayvalException()
{
Stdlib\arrayval(null);
}

public function testStrPutcsv()
{
$data = [
[
'Name' => 'John Doe',
'Age' => 45
],
[
'Name' => 'Richard Roe',
'Age' => 38
],
[
'Name' => 'Jane Roe',
'Age' => 27
]
];

$csv = <<<'CSV'
Name,Age
"John Doe",45
"Richard Roe",38
"Jane Roe",27
CSV;

$this->assertSame($csv, Stdlib\str_putcsv($data));
}
}

0 comments on commit 85baa45

Please sign in to comment.