<?PHP

/**
* read or generate Csv file
*/
class Csv{

	/**
	* read csv file to array
	* @param String $file
	* @return Array
	*/
	function GetCsv($file){

		$handle = @fopen($file, "r"); // Open file form read.

		if ($handle) {

			while(!feof($handle)){

				$line = fgets($handle);
				preg_match_all('/"(.*)"/se', $line, $matches);
				foreach($matches[0] as $v){

					$line = str_replace($v, str_replace(',', '[comma]', $v), $line);
					$line = str_replace('"', '', $line);
				}
				if(preg_match('/,/i', $line)){

					$exp_s = explode(',', $line);
					$exp_i = array();
					foreach($exp_s as $v){

						$exp_i[] = str_replace('[comma]', ',', $v);
					}
					$exp = $exp_i;
				}
				else{

					$exp_s = explode(';', $line);
					$exp_i = array();
					foreach($exp_s as $v){

						$exp_i[] = str_replace('[comma]', ',', $v);
					}
					$exp = $exp_i;
				}
				$csv[] = $exp;
			}
			fclose($handle);
			$is_empty = true;
			foreach($csv[count($csv)-1] as $v){

				if(!empty($v)){

					$is_empty = false;
				}
			}
			if($is_empty == true){

				unset($csv[count($csv)-1]);
			}
		}
		return $csv;
	}

	/**
	* make csv file
	* @param Array $data=array() - array(array('key' => 'value'))
	* @param String $file='' - fileName what to create, if not then returns the content
	*/
	function MakeCsv($data=array(), $file=''){

		$ret = '';
		$i=1;

		foreach($data as $v){

			$row = '';

			if($i == 1){

				foreach($v as $k1 => $v1){

					$row .= $row ? ';'.$k1 : $k1;
				}
				$ret .= $row."\n";
				$row = '';
			}
			foreach($v as $k1 => $v1){

				$row .= $row ? ';'.$v1 : $v1;
			}
			$ret .= $row."\n";
			$i++;
		}
		if($file){

			file_put_contents($file, utf8_decode($ret));
		}
		return $ret;
	}
}
