RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.63% (6.88%*) • Investment PI: 5.49% (6.32%*)

Create CSV File From Array With PHP

A comma-separated values (CSV) file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. The following PHP function takes an array and either returns the data to a screen or writes the array contents as a CSV file. The non-standard implementation of the CSV format means you may have to play around with the output.

PHP Function

1
<?php 
2
/*
3
 Create CSV File From Array With PHP
4
 http://www.beliefmedia.com/code/php-snippets/csv-array-php
5
*/
6
 
7
function beliefmedia_csv_array($data, $file = false, $delimiter = ',', $enclosure = '"') {
8
 
9
  $handle = fopen('php://temp', 'r+');
10
  foreach ($data as $line) fputcsv($handle, $line, $delimiter, $enclosure);
11
  rewind($handle);
12
  while (!feof($handle)) $contents .= fread($handle, 8192);
13
  fclose($handle);
14
 
15
 /* Either return to screen or write to file */
16
 if ($file === false) return $contents;
17
 else file_put_contents($file, $contents);
18
}

Sample use is as follows:

1
<?php 
2
/* Sample array */
3
$data = array(
4
  array(1, 2, 3),
5
  array('first_name', 'test, comma', 'test "quote"'),
6
);
7
 
8
/* Return to screen */
9
echo beliefmedia_csv_array($data);
10
 
11
/* Write to CSV file */
12
echo beliefmedia_csv_array($data, $file = 'test.csv');

If you're looking for a more robust solution there's plenty of CSV libraries available to handle more complex requirements.

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (California)

  Want to have a chat?
 

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment