How To Convert PHP Array To CSV File And Download Automatically.
The function convert_array_to_csv($input_array,
$download_file_name, $delimiter) have 3 parameters which is used in below
The first parameter is used to convert PHP array
to CSV and The other two parameters are used to specify the name of the
CSV file, and a delimiter.Inthis example we are using
some function i.e. fopen(), fputcsv(), fseek() and fpassthru().
fopen() : This function opens a file or URL.
fopen() takes two parameters
1.php://memory is read-write streams that allow
temporary data to be stored in a file. php://memory will always store its data in memory.
2. Mode of
the file i.e "w" (Write only. Opens and clears the contents of file;
or creates a new file if it doesn't exist).
fputcsv():This is used for formatting a line as CSV and
writes it to an open file.
fseek():This function moves the file pointer
from its current position to a new position, forward or backward,
specified by the number of bytes.
After executing fseek() in this example CSV is ready to
download. In order to download/Export the file, We use
filename="' . $download_file_name. '";');
This function tells the browser how to interpret it
content and also it tells the browser that
we want to download not display the content of the file.
fpassthru():This function reads all data from the
current position in an open file, until EOF, and writes the result to the
function convert_array_to_csv($input_array, $download_file_name, $delimiter)
$f = fopen('php://memory', 'w'); /* it will
store its data in memory */