-
-
Save rsm23/10e97caee07b84a3b7bc5d6c345a6fd8 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 namespace BayAreaWebPro\SimpleCsv; | |
| use Illuminate\Support\Collection; | |
| use SplFileObject; | |
| /** | |
| * The SimpleCsv Importer | |
| */ | |
| class SimpleCsvImporter | |
| { | |
| protected $delimiter, $enclosure, $escape; | |
| /** | |
| * Importer constructor. | |
| * @param $delimiter string | |
| * @param $enclosure string | |
| * @param $escape string | |
| */ | |
| public function __construct($delimiter = ",", $enclosure = "\"", $escape = "\\") | |
| { | |
| $this->delimiter = $delimiter; | |
| $this->enclosure = $enclosure; | |
| $this->escape = $escape; | |
| } | |
| /** | |
| * Get The File Object | |
| * @param $path string | |
| * @return iterable | |
| */ | |
| private function generateLines($path){ | |
| //Read the file contents as csv. | |
| $file = $this->getFileObject($path); | |
| while(($line = $file->fgetcsv($this->delimiter, $this->enclosure, $this->escape)) && $file->valid()) { | |
| yield $line; | |
| } | |
| //Close the file. | |
| $file = null; | |
| } | |
| /** | |
| * Import the CSV to a new Collection | |
| * @param $path string | |
| * @return Collection | |
| */ | |
| public function import($path) | |
| { | |
| $headers = array(); | |
| $lines = array(); | |
| //Get the entries as a collection. | |
| foreach($this->generateLines($path) as $index => $line){ | |
| if($index === 0){ | |
| $headers = $line; | |
| }else{ | |
| array_push($lines, array_combine($headers, $line)); | |
| } | |
| } | |
| return new Collection($lines); | |
| } | |
| /** | |
| * Get The File Object | |
| * @param $path | |
| * @return SplFileObject | |
| */ | |
| private function getFileObject($path) | |
| { | |
| return new SplFileObject($path, "r"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment