Monday, April 29, 2013

Create and download csv file from array using php


Create and download csv file from array using php.
<?php
function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $outputString = "";
    foreach($fields as $tempFields) {
        $output = array();
        foreach ( $tempFields as $field ) {
            if ($field === null && $nullToMysqlNull) {
                $output[] = "NULL";
                continue;
            }

            // Enclose fields containing $delimiter, $enclosure or whitespace
            if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
                $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
            }
            else {
                $output[] = $field;
            }
        }
        $outputString .= implode( $delimiter, $output )."\n";
    }
    return $outputString;
}
?>
Use:
<?php
$dataArray = array();
array_push($dataArray, array(
    "First Name",
    "Last Name",
    "Number",
    "Group"
));
foreach($dataList as $index => $data) {
    array_push($dataArray, array(
        "".$data["first_name"],
        "".$data["last_name"],
        "".$data["mobile_number"],
        "".$data["group_name"]
    ));
}
$csvString = arrayToCsv($dataArray);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=list.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $csvString;
?>

No comments:

Post a Comment