欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php生成txt文件實例代碼介紹

 更新時間:2016年04月28日 14:12:26   作者:途牛個人博客  
這篇文章主要為大家詳細介紹了php生成txt文件實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下

這是一個朋友過來的 php 生成 txt 文件代碼,這只是一個實例,需要我來給他生成多個 txt 文件實例的,但我覺得他這個代碼有點意思,所以就分享上來了。

先說下這個 php 生成 txt 文件代碼都是什么功能吧,肯定是要生成 txt 文件的,有點廢話了,不說其它的了,這個 php 代碼可以生成指定目錄下的一個 txt 文件,并在 txt 文件里面寫入三行文字,這個是在 php 里面定義好的。

夏日博客分享下實例的代碼如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>
<body>
<?php 
/** 
*1.前幾天一哥們工作中他們領(lǐng)導(dǎo)讓他寫一個上生成文件的類:生成文件,文件類型支持:txt、html、csv、pdf、doc(或者docx)。 
* 
*2.生成的內(nèi)容是一張表格(像html中的table),參數(shù)為:生成文件的類型、生成內(nèi)容的標題(數(shù)組),生成內(nèi)容(數(shù)組,和標題相對應(yīng))。 
*/
/************************************************* 
* 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; 
/** 
* 構(gòu)造函數(shù):初始化生成文件的目錄 
*/
public function __construct($file_dir){ 
$this->file_dir = $file_dir; 
} 
/** 
* 生成文件的入口函數(shù) 
* @string $file_name 文件名 
* @string $file_type 文件類型 
* @array $title 生成內(nèi)容的標題行 
* @array $data 生成內(nèi)容 
*/
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 內(nèi)容 
*/
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 的文件,并在里面寫入如下的內(nèi)容:

name sex age
tom boy 20
perry girl 20

以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)php程序設(shè)計有所幫助。

相關(guān)文章

最新評論