<?php
/*
* Custom CSV File Parser class v 2.0 by ajc20
*
* encode decodes csv strings and csv files
*
* Support functions:
*
* STRING csv_encode($array, $delimiter=',')
* => encodes a given array to a csv string format
*
* ARRAY csv_decode($string, $delimiter=',')
* => decodes the csv string format to an array
*
* BOOLEAN csv_encode_file($array, $file, $delimiter=',')
* => encodes the given array to csv string format
* and write it to the file
*
* ARRAY csv_decode_file($file, $delimiter=',')
* => decodes the csv file to an array data
*
*/
class libCSV{
public function csv_encode($array, $delimiter=','){
$csv_string = null;
if(is_array($array)){
$length = count($array);
for($k = 0; $k < $length; $k++){
$array[$k] = implode($delimiter, $array[$k]);
}
$csv_string = implode(PHP_EOL, $array);
} else die("The given <b><u>array</u></b> is not an array.");
return $csv_string;
}
public function csv_decode($string, $delimiter=','){
$csv_array = null;
if(is_string($string)){
if($string == "" || $string == null){
return NULL;
}
$string = preg_replace('~\r[\n]?~', "_", $string);
$rows = explode("_", $string);
$cols = Array();
$c = 0;
foreach($rows as $columns){
$cols[$c] = explode($delimiter, $columns);
$c++;
}
$csv_array = $cols;
} else die("The given <b><u>string</u></b> is not a string.");
return $csv_array;
}
public function csv_encode_file($array, $filename, $delimiter=','){
$encoded = false;
if(is_array($array)){
if(file_exists($filename)){
$data = $this->csv_encode($array, $delimiter);
$fileh = fopen($filename, 'w');
$write = fwrite($fileh, $data);
fclose($fileh);
if($write !== false);
$encoded = true;
} else die("The File ".$filename." does not exists.");
} else die("The given <b><u>array</u></b> is not an array.");
return $encoded;
}
public function csv_decode_file($filename, $delimiter=','){
$data = null;
if(file_exists($filename)){
$data = file_get_contents($filename);
$data = $this->csv_decode($data, $delimiter);
} else die("The File ".$filename." does not exists");
return $data;
}
}
?>