fork download
  1. <?php
  2. function fputcsv_content($fp, $array, $delimiter=",", $eol="\n")
  3. {
  4. static $find = ["\\r","\\n"];
  5. static $replace = ["\r","\n"];
  6. static $cycles_count = 0;
  7. $cycles_count++;
  8.  
  9. $array = array_map(function($value) use($delimiter) {
  10. return clean_value($value, $delimiter);
  11. }, $array);
  12. $eol = str_replace($find, $replace, $eol);
  13.  
  14. $line = implode($delimiter, $array) . $eol;
  15.  
  16. $return_value = $line;//fputs($fp, $line);
  17.  
  18. /** purposefully free up the ram **/
  19. $line = null;
  20. $eol = null;
  21. $array = null;
  22.  
  23. /** trigger gc_collect_cycles() every 250th call of this method **/
  24. if($cycles_count % 250 === 0) gc_collect_cycles();
  25.  
  26. return $return_value;
  27. }
  28.  
  29. /** Use a second function so the GC can be triggered here
  30.   * when it returns the value and all intermediate values are free.
  31.   */
  32. function clean_value($value, $delimeter)
  33. {
  34. /**
  35.   * use static values to prevent reassigning the same
  36.   * values to the stack over and over
  37.   */
  38. static $regex = [];
  39. static $find = "\r\n";
  40. static $replace = "\n";
  41. static $quote = '"';
  42. if(!isset($regex[$delimeter])) {
  43. $regex[$delimeter] = "/[$delimiter\"\n\r]/";
  44. }
  45. $value = trim($value);
  46. $value = str_replace($find, $replace, $value);
  47. if(preg_match($regex[$delimeter], $value)) {
  48. $value = $quote.str_replace($quote, '""', $value).$quote;
  49. }
  50. return $value;
  51. }
  52.  
  53. echo fputcsv_content(null, ['foo', "bar\n\rbaz", "hello world!",'test " test']);
Success #stdin #stdout #stderr 0.03s 26168KB
stdin
Standard input is empty
stdout
foo,"bar

baz",hello world!,"test "" test"
stderr
PHP Notice:  Undefined variable: delimiter in /home/op1lDI/prog.php on line 43