-
Notifications
You must be signed in to change notification settings - Fork 0
Excel CSV helper
Category:Helper::Community | Category:Helper::CSV
[h3]Excel CSV helper for CodeIgniter[/h3]
[url=http://maestric.com/en/doc/php/codeigniter_csv]http://maestric.com/en/doc/php/codeigniter_csv[/url]
[code]$array = array( array('Last Name', 'First Name', 'Gender'), array('Furtado', 'Nelly', 'female'), array('Twain', 'Shania', 'female'), array('Farmer', 'Mylene', 'female') );
$this->load->helper('csv'); echo array_to_csv($array);[/code]
[code] "Last Name","First Name",Gender Furtado,Nelly,female Twain,Shania,female Farmer,Mylene,female [/code]
Possible to directly download: [code]array_to_csv($array, TRUE)[/code]
[code]<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// ------------------------------------------------------------------------
/**
- CSV Helpers
- Inspiration from PHP Cookbook by David Sklar and Adam Trachtenberg
- @author Jérôme Jaglale
- @link http://maestric.com/en/doc/php/codeigniter_csv */
// ------------------------------------------------------------------------
/**
-
Array to CSV
-
download == "" -> return CSV string
-
download == "toto.csv" -> download file toto.csv */ if ( ! function_exists('array_to_csv')) { function array_to_csv($array, $download = "") { ob_start(); $f = fopen('php://output', 'w') or show_error("Can't open php://output"); $n = 0;
foreach ($array as $line) { $n++; if ( ! fputcsv($f, $line)) { show_error("Can't write line $n: $line"); } } fclose($f) or show_error("Can't close php://output"); $str = ob_get_contents(); ob_end_clean();if ($download == "") { return $str; } else { header('Content-Type: application/csv'); header('Content-Disposition: attachement; filename="' . $download . '"'); echo $str; }
} }
// ------------------------------------------------------------------------
/**
-
Query to CSV
-
download == "" -> return CSV string
-
download == "toto.csv" -> download file toto.csv */ if ( ! function_exists('query_to_csv')) { function query_to_csv($query, $headers = TRUE, $download = "") { if ( ! is_object($query) OR ! method_exists($query, 'list_fields')) { show_error('invalid query'); }
$array = array(); if ($headers) { $line = array(); foreach ($query->list_fields() as $name) { $line[] = $name; } $array[] = $line; } foreach ($query->result_array() as $row) { $line = array(); foreach ($row as $item) { $line[] = $item; } $array[] = $line; } echo array_to_csv($array, $download);
} }
/* End of file csv_helper.php / / Location: ./system/helpers/csv_helper.php */[/code]