Skip to content

Instantly share code, notes, and snippets.

@iammerrick
Created January 22, 2011 00:00
Show Gist options
  • Save iammerrick/790675 to your computer and use it in GitHub Desktop.
Save iammerrick/790675 to your computer and use it in GitHub Desktop.
<?php
/**
* CSV Class
*/
class CSV
{
public static function factory($path = NULL)
{
return new self($path);
}
public function __construct($path)
{
$this>from_file($path);
}
public 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