php產生txt檔案標題及內容的方法_php技巧

來源:互聯網
上載者:User
複製代碼 代碼如下:

<?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 "產生失敗";
}

?>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.