@@ -53,3 +53,47 @@ function arrayval($subject)
5353 get_php_type ($ subject )
5454 ));
5555}
56+
57+ /**
58+ * Format the given input array as CSV string and return it
59+ *
60+ * The input array is always expected to be an array of rows.
61+ * The keys of the first row will be automatically used as the header row.
62+ *
63+ * @param iterable $data
64+ * @param string $delimiter Field delimiter
65+ * @param string $enclosure Field enclosure
66+ * @param string $escape Escape character
67+ *
68+ * @return string
69+ *
70+ * @throws \InvalidArgumentException
71+ */
72+ function str_putcsv ($ data , $ delimiter = ', ' , $ enclosure = '" ' , $ escape = '\\' )
73+ {
74+ $ fp = fopen ('php://temp ' , 'r+b ' );
75+
76+ if (! is_iterable ($ data )) {
77+ throw new \InvalidArgumentException (sprintf (
78+ 'str_putcsv expects arrays or instances of Traversable. Got %s instead. ' ,
79+ get_php_type ($ data )
80+ ));
81+ }
82+
83+ foreach ($ data as $ row ) {
84+ fputcsv ($ fp , array_keys ($ row ), $ delimiter , $ enclosure , $ escape );
85+
86+ break ;
87+ }
88+
89+ foreach ($ data as $ row ) {
90+ fputcsv ($ fp , $ row , $ delimiter , $ enclosure , $ escape );
91+ }
92+
93+ rewind ($ fp );
94+ $ csv = stream_get_contents ($ fp );
95+ fclose ($ fp );
96+ $ csv = rtrim ($ csv , "\n" ); // fputcsv adds a newline
97+
98+ return $ csv ;
99+ }
0 commit comments