這是一個朋友過來的 php 產生 txt 檔案代碼,這隻是一個執行個體,需要我來給他產生多個 txt 檔案執行個體的,但我覺得他這個代碼有點意思,所以就分享上來了。
先說下這個 php 產生 txt 檔案代碼都是什麼功能吧,肯定是要產生 txt 檔案的,有點廢話了,不說其它的了,這個 php 代碼可以產生指定目錄下的一個 txt 檔案,並在 txt 檔案裡面寫入三行文字,這個是在 php 裡面定義好的。
夏日部落格分享下執行個體的代碼如下:
<!doctype html><html><head><meta charset="utf-8"><title>無標題文檔</title></head><body><?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 "產生失敗"; }?></body></html>
需要在 E 盤下面建立 dev 檔案夾,然後進行運行即可看到效果,運行成功,會在 dev 檔案夾下面產生一個 test.txt 的檔案,並在裡面寫入如下的內容:
name sex age
tom boy 20
perry girl 20
以上就是本文的全部內容,希望對大家學習php程式設計有所協助。