Last active
August 29, 2015 14:22
-
-
Save mokanfar/76b4fbdd8f5db0d81bf5 to your computer and use it in GitHub Desktop.
CSV -> PHP Array -> HTML Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Convert a comma separated file into an associated array then spit out html string in variable. | |
* Useful for generating one-off html block fragrments. | |
* The first row should contain the array keys. | |
* | |
* Example: | |
* | |
* @param string $filename Path to the CSV file | |
* @param string $delimiter The separator used in the file | |
* @return array | |
* @link http://gist.github.com/385876 | |
* @author Jay Williams <http://myd3.com/> | |
* @copyright Copyright (c) 2010, Jay Williams | |
* @license http://www.opensource.org/licenses/mit-license.php MIT License | |
*/ | |
ini_set('display_errors', 'on'); | |
function csv_to_array($filename='', $delimiter=',') | |
{ | |
if(!file_exists($filename) || !is_readable($filename)) | |
return FALSE; | |
$header = NULL; | |
$data = array(); | |
if (($handle = fopen($filename, 'r')) !== FALSE) | |
{ | |
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) | |
{ | |
if(!$header) | |
$header = $row; | |
else | |
$data[] = array_combine($header, $row); | |
} | |
fclose($handle); | |
} | |
return $data; | |
} | |
/** | |
* Example | |
*/ | |
$array = csv_to_array('example.csv'); | |
/** | |
* Spit out Html in browser | |
*/ | |
foreach ($array as $key => $value) { | |
echo <<<EOD | |
<h1>{$array[$key]['csvColumnHeader1']}</h1> | |
<h1>{$array[$key]['csvColumnHeader2']}</h1> | |
<h1>{$array[$key]['csvColumnHeader3']}</h1> | |
<h1>{$array[$key]['csvColumnHeader4']}</h1> | |
EOD; | |
} | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment