CsvTool.php - Sourcecode
A single and all-included CSV solution for PHP4 - should also work in php5. NEW: Now with multiline-CSV support!
<?php
class CSV {
/*
* This class helps to create and read csv-files
*/
var $_header = array();
var $_data = array();
var $enclosure = '"';
var $seperator = ";";
var $newline = "\n";
function CSV($seperator=";", $enclosure='"', $newline="\n") {
$this->seperator = $seperator;
$this->enclosure = $enclosure;
$this->newline = $newline;
}
function header($list=NULL) {
/* sets header if called with $list. Otherwise returns the
* csv-representation of the header
*/
if ($list) $this->header = $list;
else return $this->_csv($this->header);
}
function append($list) {
$this->_data[] = $list;
}
function _readLine($filehandle) {
$d = fgetcsv($filehandle, 4096, $this->seperator, $this->enclosure);
if (count($d)==1 && isset($d[0]) && $d[0]=="") return false;
return $d;
}
function read($filehandle) {
while (!feof($filehandle)) {
if ($dataline = $this->_readLine($filehandle)) {
$this->_data[] = $dataline;
}
}
}
function readFile($filename) {
$fh = fopen($filename, "r");
$this->read($fh);
fclose($fh);
}
function data() {
return $this->_data;
}
function _csvData() {
/* returns the csv-representation of the data */
$ret = array();
foreach ($this->_data as $line) {
$ret[] = $this->_csv($line);
}
return join($this->newline, $ret);
}
function _csv($list) {
$d = array();
foreach ($list as $item) {
$quote = '';
# add " around item if it contains illegal chars or is multiline
if (strpos($item, $this->enclosure)!==FALSE or strpos($item, $this->seperator)!==FALSE or strpos($item, $this->newline)!==FALSE)
$quote = $this->enclosure;
# replace " by "" (or ' by '')
$item = str_replace($this->enclosure, $this->enclosure.$this->enclosure, $item);
$d[] = $quote.$item.$quote;
}
return join($this->seperator, $d);
}
function __str() {
/*
* This exports the state as csv (=representation of this class)
*/
$header = $this->header();
if ($header)
$header .= $this->newline;
return $header.$this->_csvData();
}
}
?>

