/ Published in: PHP
Class that convert arrays to csv format, downloads CSV files and saves to disk on server.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php class CSVData { public $colDelimiter = ';'; public function __construct($colDelimiter = ';') { $this->colDelimiter = $colDelimiter; } /** * Converts an array of data to CSV format. * * @param string $head The CSV header. Example: array('User id', 'User Name', 'User Email'); * @param string $data The CSV data. Example: * array( * array(1, 'John', '[email protected]' ), * array(2, 'Andrew', '[email protected]'), * array(3, 'Ana', '[email protected]' ) * ); * @return string The Proper formatted CSV string */ public function arrayToCSV($head, $data) { $csv = ''; return $csv; } /** * Downloads CSV string to client as a file * @param string $csv A properly formatted CSV string * @param string $fileName Name of the file to be downloaded. Example: 'mycsv' * @param bool $noCache [Optional] If true, headers will be sent to prevent * browser caching of the CSV. */ public function downloadCSV($csv, $fileName, $noCache = false) { if($noCache) $this->_noCacheHeaders(); echo $csv; } /** * Saves a CSV string as a CSV file in the server * @param string $csv A properly formatted CSV string * @param string $path Where to save the file. Example: archives/csv/. * Notice the / at the end of the path. * @param string $fileName Name of the file to be saved. Example: 'mycsv' */ public function saveCSV($csv, $path, $fileName) { if($handle === false) throw new Exception( 'Could not create file: ' . $path . $fileName . '.csv' ); } ////////////////////////////////////////////////////////////////////////////////////////// //PRIVATES ////////////////////////////////////////////////////////////////////////////////////////// /** Quotes CSV column if necessary. */ private function _quoteStr($str) { { } return $str; } /** Sends no caching headers to browser. */ private function _noCacheHeaders() { } } //Usage of class ); $csv = new CSVData(); //Create a new instance //Transform the array to CSV string $csvStr = $csv->arrayToCSV($head, $data); //Download CSV, the browser will prompt //the user to download the file $csv->downloadCSV($csvStr, 'users', true); //Whrite csv data to the server $csv->saveCSV($csvStr, 'archives/csv/', 'users'); ?>