Copy Code code as follows:
<?php
/**
*1. A couple of days ago, a guy at work, they led him to write a class that generates files: Makefile, file type support: TXT, HTML, CSV, PDF, doc (or docx).
*
*2. The generated content is a table (like a table in HTML), with parameters: the type of the generated file, the title (array) of the generated content, the generated content (array, and the caption corresponds).
*/
/*************************************************
* Class Name:createfile
* Description:create different type files
* Author:fenghuo
* DATE:2013-11-12
************************************************/
/**
*3. I used the evenings to help him organize a file class that generates TXT.
***/
Class createfile{
public $file _type;
public $file _name;
public $file _dir;
/**
* Constructor: directory that initializes the generated file
*/
Public function __construct ($file _dir) {
$this->file_dir = $file _dir;
}
/**
* Generate File Entry function
* @string $file _name file name
* @string $file _type file type
* @array $title the header row of the generated content
* @array $data Generate content
*/
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;
# Test points
echo $fun, '--------------<br/> ';
if (Method_exists ($this, $fun))
{
$file = $file _name. ". $file _type;
$this-> $fun ($file, $title, $data);
return true;
}else{
return "no!";
}
}
/**
* Generate TXT type file
* @string $file filename
* @array $title Title
* @array $data Content
*/
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";
}
# Test points
Echo $this->file_dir. $file, '-----123---------<br/> ';
$fp = fopen ($this->file_dir. $file, "A +");
Fwrite ($fp, $string);
Fclose ($FP);
return true;
}
}
//**************************************
Test
$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 "Build Success";
}else{
echo "Build Failed";
}
?>