Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created January 21, 2011 23:42
Show Gist options
  • Select an option

  • Save ryanflorence/790657 to your computer and use it in GitHub Desktop.

Select an option

Save ryanflorence/790657 to your computer and use it in GitHub Desktop.
<?php
/**
* CSV Class
*/
class CSV
{
public static function from_file($path = '')
{
$csv = array();
if (($handle = fopen($path, "r")) !== FALSE)
{
while ($line = fgetcsv($handle, 1000, ",")) $csv[] = $line;
fclose($handle);
}
else
{
echo "Could not open csv file at $path";
}
return $csv;
}
/**
* Takes an array and returns an associative array with the first line
* acting as the keys for all other line's fields.
*
* @param array $arr the array to convert
* @return the new associative array
* @author Ryan Florence
*/
public static function to_assoc($arr = array())
{
$data = array();
$header = array_shift($arr);
foreach ($arr as $line)
{
$assoc_line = array();
foreach($line as $i => $field)
{
$assoc_line[$header[$i]] = $field;
}
$data[] = $assoc_line;
}
return $data;
}
// from comments in http://php.net/manual/en/function.fputcsv.php, looks good enough
public static function sputcsv($row, $delimiter = ',', $enclosure = '"', $eol = "\n")
{
static $fp = false;
if ($fp === false)
{
$fp = fopen('php://temp', 'r+'); // see http://php.net/manual/en/wrappers.php.php - yes there are 2 '.php's on the end.
// NB: anything you read/write to/from 'php://temp' is specific to this filehandle
}
else
{
rewind($fp);
}
if (fputcsv($fp, $row, $delimiter, $enclosure) === false)
{
return false;
}
rewind($fp);
$csv = fgets($fp);
if ($eol != PHP_EOL)
{
$csv = substr($csv, 0, (0 - strlen(PHP_EOL))) . $eol;
}
return $csv;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment