Last active
April 10, 2019 18:44
-
-
Save Nickster258/5a9e46cdfa386ca7cba88dc10f0fa4da to your computer and use it in GitHub Desktop.
A basic CSV loader class for PHP
This file contains 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 | |
class CSVLoad { | |
private $raw_data; | |
private $data_key; | |
private $lines; | |
private $position; | |
public function __construct($filename) { | |
$this->raw_data = array_map('str_getcsv', file($filename)); | |
$this->data_key = $this->raw_data[0]; | |
$this->lines = sizeof($this->raw_data) - 1; | |
$this->position = 0; | |
} | |
public function getRaw() { | |
return $this->raw_data; | |
} | |
public function getKey() { | |
return $this->data_key; | |
} | |
public function getLine($index) { | |
return $this->raw_data[$index+1]; | |
} | |
public function hasNext() { | |
if ($this->position >= $this->lines) { | |
return false; | |
} | |
return true; | |
} | |
public function getNext() { | |
if ($this->position >= $this->lines) return -1; | |
++$this->position; | |
$tmp_data = []; | |
for ($i = 0; $i < sizeof($this->data_key); $i++) { | |
$tmp_data[$this->data_key[$i]] = $this->raw_data[$this->position][$i]; | |
} | |
return $tmp_data; | |
} | |
} | |
?> |
This file contains 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 | |
require_once "CSVLoad.php"; | |
class LoadPipeAsCSV extends CSVLoad { | |
public function __construct($filename, $fields) { | |
$tmpfile = tmpfile(); | |
$csvstr = ""; | |
// Insert field names | |
foreach ( $fields as &$tmp) { | |
$csvstr = $csvstr . $tmp . ","; | |
} | |
// Distinguish the fields as its own line and remove trailing comma | |
$csvstr = substr($csvstr, 0, -1) . "\n"; | |
// Load the contents with | replaced with , | |
if ($file = fopen($filename, "r")) { | |
while(!feof($file)) { | |
$line = preg_replace('~[\r\n]+~', '', str_replace("|", ",", fgets($file))); | |
if ($line == "") break; | |
$csvstr = $csvstr . $line . ",\n"; | |
} | |
fclose($file); | |
} | |
fwrite($tmpfile, $csvstr); | |
parent::__construct(stream_get_meta_data($tmpfile)['uri']); | |
fclose($tmpfile); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment