Skip to content

Instantly share code, notes, and snippets.

@mokanfar
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mokanfar/76b4fbdd8f5db0d81bf5 to your computer and use it in GitHub Desktop.
Save mokanfar/76b4fbdd8f5db0d81bf5 to your computer and use it in GitHub Desktop.
CSV -> PHP Array -> HTML Generator
<?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