Intycsv class csv en php simple et intuitive

Description

Cette classe que j'ai construite est un objet à caractère intuitif permettant de générer un fichier csv:
- à partir d'une table Mysql.
- à partir de données brut.

Elle permet aussi de modifier le contenu d'un fichier.

Le caractère principal de cet objet est son intuitivité sur l'appel des méthodes.

Pour toutes questions ou bugs reportés, je reste joignable.

Source / Exemple :


<?php
######################################################################################## 
########################################################################################
###
###  From gross content in csv format from database or personnal creation, manage and deliver in csv file.	 
###  	 
###	 @name csv 
###	 @author Edoaurd Kombo <edouard.kombo@live.fr>
###
######################################################################################## 
########################################################################################

class intyCsv {

	protected $_firstDelimiter		= '';				//First symbol(s) used to separate columns	
	protected $_lastDelimiter		= ';';				//Last symbol(s) used to separate columns	
	protected $_cut					= '÷';				//Cut csv every
	protected $_header				= false;			//Set file header
	protected $_file;									//File directory
	protected $_chmod				= 0777;				//CHMOD
	protected $_path;									//File path
	protected $_name;									//File name
	protected $_content             = array();			//Content of file

	
	function __conbstruct(){}
	
	function __destruct(){}		
	
	///////////////////////////////////////////
	///////////////////////////////////////////
	// SETTERS & GETTERS
	///////////////////////////////////////////
	///////////////////////////////////////////
	
		///////////////////////////////////////////
		// SETTERS
		///////////////////////////////////////////
		
		private function setFile($path , $name){ //Set the file name and path (can be overwritten)
			
			$this->_path = $path;
			
			$this->testDirectory($this->_path);
			
			$this->_name = $name;
			
			return $this->_file = $this->_path.$this->_name;
		}
		
		private function setChmod($chmod){ //Set the file name and path (can be overwritten)
			
			return $this->_chmod = $chmod;
		}		
		
		private function setDelimiters($first , $last){ //Optional (delimiters can be only ";" for classic csv documents)
		
			$this->_firstDelimiter = (empty($first)) ? $this->_firstDelimiter : $first ;
			$this->_lastDelimiter  = (empty($last)) ? $this->_lastDelimiter : $last ;
			
			return array($this->_firstDelimiter , $this->_lastDelimiter);
		}

		private function setHeader($header){ //We construct a header ('name;firstname;phone;zip;')
		
			return $this->_header = $header;
		}	
		
		private function setContent($content){ //We add new lines to content and avoid an empty line at the end file
		
			return $this->_content = $content;
		}
		
		private function setFopenCut($symbol){ //Optional (symbol for fopen cutting ";" or "," or other)
			
			return $this->_cut = $symbol;
		}		
	
		///////////////////////////////////////////
		// GETTERS
		///////////////////////////////////////////			
		
		private function getLines(){ //Get Lines of the csv content after "open" action
		
			try {
			
				if(is_array($this->_content) && count($this->_content) >= 1){
				
					return $this->_content;
				
				} else {
				
					$error = 'Unable to fetch the number of lines in the csv file.';
					throw new Exception($error);
				}
			
			} catch(Exception $e) {
			
				echo 'Exception caught: '.$e->getMessage()."\n";
			}
		}
		
		private function getFile(){
		
			$file = array();
			$file['name'] = $this->_name;
			$file['path'] = $this->_path;
			return $file;
		}
		
		private function getCounter(){
		
			$file = array();
			$file['name'] = $this->_name;
			$file['path'] = $this->_path;
			return $file;
		}

		
	///////////////////////////////////////////
	///////////////////////////////////////////
	// AGENTS
	///////////////////////////////////////////
	///////////////////////////////////////////
	
	private function fetchArray(){ //Export content in array for view (if content has been directly set by another program)
		
		$cont = explode("\n" , $this->_content);

		$tab = array();
		
		foreach($cont as $key => $val){ //Fetch content line per line
		
			$val = str_replace($this->_firstDelimiter , '' , $val); //We retire first delimiter
			
			$content = explode($this->_lastDelimiter , $val); //We now fetch column per column
			
			$tab[$key] = array();
			
			foreach($content as $cey => $cal){
			
				array_push($tab[$key] , $cal);
			}
		}	
		
		return $tab;
	}

	private function fetchFromTable(){ //Export content in array for view (if content has been directly set by another program)
		
		$content = '';
		
		foreach($this->_content as $key => $val){ //Fetch content line per line
		
			$nb = 0;
		
			foreach($val as $kk => $vv){
				
				$nb++;

				//Insert tabulation at the end of the line only if not the file last line
				if($nb < count($val)){
				
					$content .= $this->_firstDelimiter.$vv.$this->_lastDelimiter;
				
				} else {
					
					$content .= (($key + 1) < count($this->_content)) ? $this->_firstDelimiter.$vv."\n" : $this->_firstDelimiter.$vv ;					
				}					
			}
		}	
		
		return $this->_content = $content;
	}	
	
	private function testDirectory($fullpath){
	
		if(!empty($fullpath)){
		
			$directory = explode('/' , $fullpath);
			if(is_array($directory)){
			
				$path = '';
				
				foreach($directory as $key => $val){
				
					//We create new directory except last value of the array which is a file
					if(($key+1) < count($directory)){
						
						$path .= (($key+1) == (count($directory) - 1)) ? $val : $val.'/' ;
					}
				}
				
				//We create directory if does not exists
				if(!is_dir($path)){
					
					mkdir($path , $this->_chmod);
				}
			}		
		}		
	}		
		
		
		
	///////////////////////////////////////////
	///////////////////////////////////////////
	// ACTIONS
	///////////////////////////////////////////
	///////////////////////////////////////////
	
	function set($args){
		
		switch($args[0]){
			
			case 'file': $result = $this->setFile($args[1] , $args[2]);			    
			break;
			case 'delimiters': $result = $this->setDelimiters($args[1] , $args[2]);	
			break;
			case 'header': $result = $this->setHeader($args[1]);			        
			break;			
			case 'content': $result = $this->setContent($args[1]);		
			break;
			case 'fopencut': $result = $this->setFopenCut($args[1]);		
			break;
			case 'chmod': $result = $this->setChmod($args[1]);		
			break;			
		}
		return $result;
	}
	
	function get($args){
		
		switch($args[0]){
			
			case 'content': $result = $this->_content;                              
			break;
			case 'file': $result = $this->getFile();                              
			break;			
		}
		return $result;
	}

	function datas($args){ //Everything about data treatment
	
		switch($args[0]){

			case 'fetchArray': $result = $this->fetchArray();                              
			break;
			case 'fromTable': $result = $this->fetchFromTable();                              
			break;			
		}
		return $result;		
	}

	function compile(){ //We add the header to the content property (if we set a header)
		
		$content = (is_array($this->_content)) ? $this->fetchFromTable() : $this->_content ;
		
		return $this->_content = ($this->_header != false) ? $this->_header."\n".$content : $content ;
	}

	function download(){ //Download the file directly in the browser after saving
		
		// Set headers
		header("Cache-Control: public");
		header("Content-Description: File Transfer");
		header("Content-Disposition: attachment; filename=".$this->_file."");
		header("Content-Type: application/php");
		header("Content-Transfer-Encoding: binary");
		echo $this->_content;
	}
	
		///////////////////////////////////////////
		// RCSD Method (Read, create, save, delete)
		///////////////////////////////////////////
		
		function read(){ //Open csv file and fetch content like it is()
			
			if(($handle = fopen($this->_file, "r")) !== FALSE) {
			
				while(($data = fgetcsv($handle, 1000, $this->_cut)) !== FALSE) {
				
					$num = count($data);

					for ($c=0; $c < $num; $c++) {
					
						str_replace($this->_firstDelimiter , '' , $data[$c]); //We retire first delimiter
						
						$content = explode($this->_lastDelimiter , $data[$c]); //We now fetch column per column
												
						array_push($this->_content , $content);						
					}
				}
				fclose($handle);
			}

			return $this->_content;
		}

		
		function copy($newPath){
		
			$this->testDirectory($newPath);
			
			try {
			
				if(!copy($this->_file , $newPath)){
				
					$error = 'Unable to copy "'.$this->_file.'" to directory "'.$newPath.'".';
					throw new Exception($error);
				}
				
			} catch(Exception $e) {
			
				echo 'Exception caught: '.$e->getMessage()."\n";			
			}	
		}	
		
		function save(){
		
			$fp = fopen($this->_file , "w");
			
			try {
			
				if($fp){
				
					fwrite($fp , $this->_content); // insert le texte dans le fichier. 
					fclose($fp);
				
				} else {
					
					$error = 'Unable to open "'.$this->_file.'" for saving.';
					throw new Exception($error);
				}
			
			} catch(Exception $e) {
				
				echo 'Exception caught: '.$e->getMessage()."\n";
			}		
		}
		
		function delete($file){
		
			try{
			
				$content = (!empty($file)) ? $file : $this->_file ;
				
				if(is_file($content)){
						
					unlink($content);
				
				} else {
				
					$error = 'Unable to delete "'.$content.'". ';
					throw new Exception($error);
				}
				
			} catch(Exception $e) {
			
				echo 'Exception caught: '.$e->getMessage()."\n";
			}		
		}
}

Conclusion :


APPLICATION DE L'OBJET:

//Create basic csv
$csv = new intyCsv();
$csv->set(array('header' , 'Name;Firstname;Date')); //Add header

//Add content
$content = 'Kombo;Edouard;'.date("Y")."\n";
$content .= 'Doe;John;'.date("Y");

$csv->set(array('content' , $content)); //Add content
$csv->compile(); //Assign header+content to $this->_content
$csv->set(array('file' , $path = NULL , 'test.csv')); //Define file path + name
$csv->save();

//$csv->download(); //For direct download on the browser

-------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------

//Generate csv from datas table
$csv = new csv();
$csv->set(array('header' , 'Name;Firstname;Date')); //Add header
$csv->set(array('delimiters' , '' , ';')); //Add delimiters (separators of the csv file

//Add content
$content = array(array('Kombo', 'Edouard', date('Y')) , array('Doe', 'John', date('Y')));
$csv->set(array('content' , $content)); //Add content
$csv->compile(); //Assign header+content to $this->_content
$csv->set(array('file' , $path = NULL , 'test.csv')); //Define file path + name
$csv->save();

-------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------

//Reorganize csv datas
$csv = new csv();
$csv->set(array('file' , $path = NULL , 'test.csv')); //We fetch the file previously created
$datas = $csv->read();

//We change the content of $datas
foreach($datas as $key => $val){

foreach($val as $kk => $vv){

//We inverse position of name and firstname in the corresponding array
if($val[0] == 'Kombo'){

$val[0] = 'Edouard';
$val[1] = 'Kombo';
}
}
$datas[$key] = $val; //New value to $datas
}

//Saving in the same file
/*
$csv->set(array('content' , $datas)); //We set the new content to the file
$csv->compile();
$csv->save();
  • /


//Saving in another file
$csv->set(array('content' , $datas)); //We set the new content to the file
$csv->set(array('file' , $path = NULL , 'new_test.csv')); //We set the new content to the file
$csv->compile();
$csv->save();

//Copy this file in another path
$csv->copy('test/retest/test2.php');

//Delete files
$csv->delete();

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.