php convert array to csv file code example

Example 1: php read csv to array

$lines =file('CSV Address.csv');

foreach($lines as $data)
{
list($name[],$address[],$status[])
= explode(',',$data);
}

Example 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
*/

Example 3: php array to csv string

To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on failure.

Syntax :

fputcsv( file, fields, separator, enclosure, escape )
  
Example:
<?php 
  
// Create an array of elements 
$list = array( 
    ['Name', 'age', 'Gender'], 
    ['Bob', 20, 'Male'], 
    ['John', 25, 'Male'], 
    ['Jessica', 30, 'Female'] 
); 
   
// Open a file in write mode ('w') 
$fp = fopen('persons.csv', 'w'); 
  
// Loop through file pointer and a line 
foreach ($list as $fields) { 
    fputcsv($fp, $fields); 
} 
  
fclose($fp); 
?>

Example 4: convert array to csv laravel

/**
 * Takes in a filename and an array associative data array and outputs a csv file
 * @param string $fileName
 * @param array $assocDataArray     
 */
public function outputCsv($fileName, $assocDataArray)
{
    ob_clean();
    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private', false);
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment;filename=' . $fileName);    
    if(isset($assocDataArray['0'])){
        $fp = fopen('php://output', 'w');
        fputcsv($fp, array_keys($assocDataArray['0']));
        foreach($assocDataArray AS $values){
            fputcsv($fp, $values);
        }
        fclose($fp);
    }
    ob_flush();
}
// Call function
  $allData = Subscription::all();
  $data = array();
	foreach ($allData as $key => $value) 
	{
		$fields = array( 'S.No' => $value->id, 'Email' => $value->email, 'Date' => date('Y-m-d',strtotime($value->created_at)));
		$data[] = $fields;
	}
	$filename = date('Y-m-d H:i:s').' - subcription_data.csv';
	outputCsv($filename, $data);

Example 5: csv to array php

$csv = array_map('str_getcsv', file('data.csv'));

Tags:

Php Example