Skip to main content

PHP : Creating a CSV file as download file from array

Few days earlier I need to Create a text Or SCV file what will return some of the datafeed. Condition is i can't save the file in the serve i have to create and make to download for the user.

So i made the below function  

function genarateFeedTextFile($data=array(),$file_name=''){
$text='';
$temp=array();

if($data){
foreach($data as $value){
         $text .= implode("\t",$value)."\n"; }
}
header("Content-Type: text/plain");
header("Content-disposition: attachment; filename=".$file_name.".txt"); 
header("Content-Transfer-Encoding: binary"); 
header("Pragma: no-cache"); 
header("Expires: 0");
echo $text;
}


This function solved my problem. But soon i have a little more problem. Some of my data contain new line "\n" or "\r" to tab "\b" so the result was not expected so i made a new function and puss all the string data through .

function simpletext($string){
$search=array("\n","\r","\t");
$string=str_replace($search,' ',$string);
$string=strip_tags($string);
return $string;
}

hope this can help some of you .

Comments