php生成txt文件標題及內容

<?php
/**
*1.前幾天一哥們工作中他們領導讓他寫一個上生成文件的類:生成文件,文件類型支持:txt、html、csv、pdf、doc(或者docx)。
*
*2.生成的內容是一張表格(像html中的table),參數為:生成文件的類型、生成內容的標題(數組),生成內容(數組,和標題相對應)。 
 */
/*************************************************
* class name:createFile
* description:create different type files
* author:fenghuo
* date:2013-11-12
************************************************/
/**
*3.我利用晚上的時間幫他就整理瞭一個生成txt的文件類.
***/
class createFile{
	public $file_type;
	public $file_name;
	public $file_dir;
	/**
       *  構造函數:初始化生成文件的目錄
       */
	public function __construct($file_dir){
		$this->file_dir = $file_dir;
	}
	/**
       * 生成文件的入口函數
       * @string $file_name 文件名
       * @string $file_type 文件類型
       * @array $title 生成內容的標題行
       * @array $data 生成內容
       */
	public function create_file($file_name,$file_type,$title,$data){
		if(empty($data)){
			return false;
		}
		if(!empty($title)){
			if(count($title) != count($data[0])){
				return false;
			}
		}
		if($file_name == ""){
			$file_name = $this->file_name;

		}
		if($file_type == ""){
			$file_type = $this->file_type;
		}
		$fun = 'mk_'.$file_type;
		# 測試點
		echo $fun,'--------------<br/>';
		if( method_exists( $this,$fun))
		{
			$file = $file_name.".".$file_type;
			$this -> $fun ($file,$title,$data);
			return true;
		}else{
			return "NO!";
		}
	}
	/**
       *生成txt類型文件
       *@string $file 文件名
       *@array $title 標題
       *@array $data 內容
       */
	public function mk_txt($file,$title,$data){  
	    $string = "";
		if(!empty($title)){
			for( $i = 0;$i < count( $title ); $i++ ){
				$string .= ' '. mb_convert_encoding($title[$i],'GBK',"UTF-8");
			}
			$string  .="\r\n";
		}
		foreach ( $data as $key =>$var)
		{
			for( $i = 0; $i < count($data[$key]); $i++ ){
				$string .= ' '. mb_convert_encoding($data[$key][$i],'GBK',"UTF-8");
			}
			$string .="\r\n";
		}
		# 測試點
		echo $this->file_dir.$file,'-----123---------<br/>';
		$fp = fopen($this->file_dir.$file, "a+");
		fwrite($fp,$string);
		fclose($fp);
		return true;
	}

	
	}

//**************************************
//測試
$dir ='E:\dev\ ';
$file_name = "test";
$file_type = "txt";
$title     = array("name","sex","age");
$data[]    = array("tom","boy",20);
$data[]    = array("perry","girl",20);
$file      = new createFile($dir);
$flag      = $file-> create_file($file_name,$file_type,$title,$data);
if($flag == true){
	echo "生成成功";
}else{
	echo "生成失敗";
}

?>

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *