Answers for "php array to csv export"

PHP
2

php array to csv

Instead of writing out values consider using 'fputcsv()'.

This may solve your problem immediately.

function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
    $f = fopen('php://memory', 'r+');
    foreach ($data as $item) {
        fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
    }
    rewind($f);
    return stream_get_contents($f);
}

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));

/*
I hope it will help you.
Namaste
Stay Home Stay Safe
*/
Posted by: Guest on May-30-2020
0

export data to csv in php

<?php
  
//store the data that you retrieve from DB in a varible, in my case its $keywords_analytics
  
if($keywords_analytics!=''){
    $delimiter = ",";
    $fileName = 'search_terms.csv';



    // Create a file pointer
    $f = fopen('php://memory', 'w');

    // Set column headers
    $fields = array('Date', 'Search Term', 'Total');

    fputcsv($f, $fields, $delimiter);

    foreach ($keywords_analytics as $ka){
        $lineData = array($ka['dated'], $ka['keyword'], $ka['total']);
        fputcsv($f, $lineData, $delimiter);
    }
    // Move back to beginning of file
    fseek($f, 0);

    // Set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $fileName . '";');

    //output all remaining data on a file pointer
    fpassthru($f);
}
exit;
?>
Posted by: Guest on July-19-2021

Browse Popular Code Answers by Language