Posted By

section31 on 12/01/08


Tagged


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

discorax
rickfu
vali29


Array to CSV


 / Published in: PHP
 

  1. class Format {
  2. static public function arr_to_csv_line($arr) {
  3. $line = array();
  4. foreach ($arr as $v) {
  5. $line[] = is_array($v) ? self::arr_to_csv_line($v) : '"' . str_replace('"', '""', $v) . '"';
  6. }
  7. return implode(",", $line);
  8. }
  9.  
  10. static public function arr_to_csv($arr) {
  11. $lines = array();
  12. foreach ($arr as $v) {
  13. $lines[] = self::arr_to_csv_line($v);
  14. }
  15. return implode("\n", $lines);
  16. }
  17.  
  18. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: safiot on September 7, 2010

thanx a lot the code is clean and works fine!

Posted By: cainmi on February 17, 2011

If you want the column headings included, stick this in before line 15 (the final return statement): array_unshift($lines, self::arr_to_csv_line(array_keys(array_shift($arr))));

You need to login to post a comment.