Last active
December 21, 2015 01:08
-
-
Save kfriend/6225050 to your computer and use it in GitHub Desktop.
CsvArray: Simple array wrapper class for representing CSV data, with methods for converting to CSV from an array.
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 CsvArray | |
{ | |
protected $data; | |
protected $delimiter; | |
protected $enclosure; | |
protected $forceEnclosement; | |
public function __construct($data = array(), $delimiter = ',', $enclosure = '"', $forceEnclosement = false) | |
{ | |
// Double check for false values, just in case user passed NULL or FALSE to use default value | |
$this->delimiter = ($delimiter) ? $delimiter : ','; | |
$this->enclosure = ($enclosure) ? $enclosure : '"'; | |
$this->forceEnclosement = (bool) $forceEnclosement; | |
$this->setData($data); | |
} | |
/** | |
* To CSV | |
* | |
* Function adapted from http://stackoverflow.com/questions/3933668/convert-array-into-csv#12470042 | |
* | |
* @return string CSV formatted string | |
*/ | |
public function toCsv() | |
{ | |
$delimiter = preg_quote($this->delimiter, '/'); | |
$enclosure = preg_quote($this->enclosure, '/'); | |
$rows = array(); | |
foreach ($this->data as $row) | |
{ | |
$r = array(); | |
foreach ($row as $field) | |
{ | |
if ($this->forceEnclosement || preg_match("/(?:${delimiter}|${enclosure}|\s)/", $field)) | |
{ | |
$r[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, (string) $field) . $enclosure; | |
} | |
else | |
{ | |
$r[] = (string) $field; | |
} | |
} | |
$rows[] = implode($delimiter, $r); | |
} | |
return trim(implode("\n", $rows)); | |
} | |
protected function dataToArray($data) | |
{ | |
if (is_object($data)) | |
{ | |
if (method_exists($data, 'toArray')) | |
{ | |
$data = $data->toArray(); | |
} | |
elseif (method_exists($data, 'to_array')) | |
{ | |
$data = $data->to_array(); | |
} | |
} | |
if (!is_array($data)) | |
{ | |
throw new Exception('Invalid data'); | |
} | |
return $data; | |
} | |
public function setData($data) | |
{ | |
$this->data = $this->dataToArray($data); | |
} | |
public function addRow($row) | |
{ | |
$row = $this->dataToArray($row); | |
$this->data[] = $row; | |
} | |
public function appendRow($row) | |
{ | |
$this->addRow($row); | |
} | |
public function prependRow($row) | |
{ | |
$row = $this->dataToArray($row); | |
array_unshift($this->data, $row); | |
} | |
public function getData() | |
{ | |
return $this->data; | |
} | |
public function toString() | |
{ | |
return $this->toCsv(); | |
} | |
public function toArray() | |
{ | |
return $this->getData(); | |
} | |
public function __toString() | |
{ | |
return $this->toCsv(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment