Created
January 21, 2011 23:42
-
-
Save ryanflorence/790657 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| /** | |
| * 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