RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (5.84%*) • Fixed: 5.39% (5.84%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.19%*) • Investment PI: 5.49% (5.98%*)

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 complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

Like this article?

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

Leave a comment