Describes the sample code of three methods for generating word in PHP.

Source: Internet
Author: User
Principle: as an extension class of PHP, com is automatically called by the server that has installed office. application com, which can automatically generate documents. Official PHP documentation manual: www.php.netmanualenclass.com. official php instance: 1234567891011121314151617

Principle: com is an extension class of PHP. the server that has installed the office will automatically call the com of word. application to automatically generate documents,

Use official instances:

 Version}\n"; //bring it to front$word->Visible = 1; //open an empty document$word->Documents->Add(); //do some weird stuff$word->Selection->TypeText("This is a test...");$word->Documents[1]->SaveAs("Useless test.doc"); //closing word$word->Quit(); //free the object$word = null;?>

Personal suggestion: the method after the com instance needs to find the official documentation to know what it means. the editor has no code prompt, which is very inconvenient. In addition, this efficiency is not very high and is not recommended.

Using PHP to write content into a doc file can be divided into two methods:
  • Generate mht format (similar to HTML) and write it to word

  • Write word in pure HTML format

  1. Generate mht format (similar to HTML) and write it to word
/*** Obtain the content of a word document based on HTML code * create a document that is essentially mht, this function analyzes the file content and downloads image resources from the remote page * this function depends on the class of MhtFileMaker * this function analyzes the img tag and extracts the src attribute value. However, the src property value must be enclosed by quotation marks. Otherwise, the absolute path of the ** @ param string $ content HTML content * @ param string $ absolutePath webpage cannot be extracted. If the image path in the HTML content is relative, you need to fill in this parameter so that the function can automatically fill in the absolute path. This parameter must end with/* @ param bool $ isEraseLink whether to remove the link in the HTML content */function getWordDocument ($ content, $ absolutePath = "", $ isEraseLink = true) {$ mht = new MhtFileMaker (); if ($ isEraseLink) $ content = preg_replace ('/(\ s *. *? \ S *) <\/a>/I ',' $ 1', $ content); // remove the link $ images = array (); $ files = array (); $ matches = array (); // This algorithm requires that the attribute values after src must be enclosed in quotation marks if (preg_match_all ('// I', $ content, $ matches )) {$ arrPath = $ matches [1]; for ($ I = 0; $ I
 
  
AddContents ("tmp.html", $ mht-> GetMimeType ("tmp.html"), $ content); for ($ I = 0; $ I
  
   
AddContents ($ files [$ I], $ mht-> GetMimeType ($ image), $ imgcontent);} else {echo "file:". $ image. "not exist!
   
";}} Return $ mht-> GetFile ();}


Usage: The main function of remotely calling this function is to analyze all the image addresses in the HTML code and download them one by one. After obtaining the image content, call the MhtFileMaker class to add the image to the mht file. The added details are encapsulated in the MhtFileMaker class.

url= http://www.***.com; $content =file_get_contents($url); $fileContent = getWordDocument($content,"http://www.yoursite.com/Music/etc/");$fp =fopen("test.doc",'w');fwrite($fp,$fileContent);fclose($fp);


Locally generated call: where, the $ content variable should be the HTML source code, and the following link should be the URL address that can fill the relative path of the image in the HTML code

Header ("Cache-Control: no-cache, must-revalidate"); header ("Pragma: no-cache"); $ wordStr = 'php Huaibei's personal website --PHP10086.com '; $ fileContent = getWordDocument ($ wordStr); $ fileName = iconv ("UTF-8", "GBK", 'php Huaibei '. '_'. $ intro. '_'. rand (100,999); header ("Content-Type: application/doc"); header ("Content-Disposition: attachment; filename = ". $ fileName. ". doc "); echo $ fileContent;


Note: Before using this function, you must first include the MhtFileMaker class, which can help us generate Mht documents.

 Description:  The class can make .mht file.***********************************************************************/ class MhtFileMaker{    var $config =array();    var $headers =array();    var $headers_exists =array();    var $files =array();    var $boundary;    var $dir_base;    var $page_first;     function MhtFile($config =array()){     }     function SetHeader($header){        $this->headers[] =$header;        $key =strtolower(substr($header, 0, strpos($header,':')));        $this->headers_exists[$key] = TRUE;    }     function SetFrom($from){        $this->SetHeader("From: $from");    }     function SetSubject($subject){        $this->SetHeader("Subject: $subject");    }     function SetDate($date = NULL, $istimestamp = FALSE){        if ($date == NULL) {            $date = time();        }        if ($istimestamp == TRUE) {            $date =date('D, d M Y H:i:s O',$date);        }        $this->SetHeader("Date: $date");    }     function SetBoundary($boundary = NULL){        if ($boundary == NULL) {            $this->boundary ='--' .strtoupper(md5(mt_rand())) .'_MULTIPART_MIXED';        }else {            $this->boundary =$boundary;        }    }     function SetBaseDir($dir){        $this->dir_base =str_replace("\\","/",realpath($dir));    }     function SetFirstPage($filename){        $this->page_first =str_replace("\\","/",realpath("{$this->dir_base}/$filename"));    }     function AutoAddFiles(){        if (!isset($this->page_first)) {            exit ('Not set the first page.');        }        $filepath =str_replace($this->dir_base,'',$this->page_first);        $filepath ='http://mhtfile' .$filepath;        $this->AddFile($this->page_first,$filepath, NULL);        $this->AddDir($this->dir_base);    }     function AddDir($dir){        $handle_dir = opendir($dir);        while ($filename = readdir($handle_dir)) {            if (($filename!='.') && ($filename!='..') && ("$dir/$filename"!=$this->page_first)) {                if (is_dir("$dir/$filename")) {                    $this->AddDir("$dir/$filename");                }elseif (is_file("$dir/$filename")) {                    $filepath =str_replace($this->dir_base,'',"$dir/$filename");                    $filepath ='http://mhtfile' .$filepath;                    $this->AddFile("$dir/$filename",$filepath, NULL);                }            }        }        closedir($handle_dir);    }     function AddFile($filename,$filepath = NULL,$encoding = NULL){        if ($filepath == NULL) {            $filepath =$filename;        }        $mimetype =$this->GetMimeType($filename);        $filecont =file_get_contents($filename);        $this->AddContents($filepath,$mimetype,$filecont,$encoding);    }     function AddContents($filepath,$mimetype,$filecont,$encoding = NULL){        if ($encoding == NULL) {            $filecont =chunk_split(base64_encode($filecont), 76);            $encoding ='base64';        }        $this->files[] =array('filepath' =>$filepath,                               'mimetype' =>$mimetype,                               'filecont' =>$filecont,                               'encoding' =>$encoding);    }     function CheckHeaders(){        if (!array_key_exists('date',$this->headers_exists)) {            $this->SetDate(NULL, TRUE);        }        if ($this->boundary == NULL) {            $this->SetBoundary();        }    }     function CheckFiles(){        if (count($this->files) == 0) {            return FALSE;        }else {            return TRUE;        }    }     function GetFile(){        $this->CheckHeaders();        if (!$this->CheckFiles()) {            exit ('No file was added.');        }        $contents = implode("\r\n",$this->headers);        $contents .="\r\n";        $contents .="MIME-Version: 1.0\r\n";        $contents .="Content-Type: multipart/related;\r\n";        $contents .="\tboundary=\"{$this->boundary}\";\r\n";        $contents .="\ttype=\"" .$this->files[0]['mimetype'] . "\"\r\n";        $contents .="X-MimeOLE: Produced By Mht File Maker v1.0 beta\r\n";        $contents .="\r\n";        $contents .="This is a multi-part message in MIME format.\r\n";        $contents .="\r\n";        foreach ($this->filesas $file) {            $contents .="--{$this->boundary}\r\n";            $contents .="Content-Type: $file[mimetype]\r\n";            $contents .="Content-Transfer-Encoding: $file[encoding]\r\n";            $contents .="Content-Location: $file[filepath]\r\n";            $contents .="\r\n";            $contents .=$file['filecont'];            $contents .="\r\n";        }        $contents .="--{$this->boundary}--\r\n";        return $contents;    }     function MakeFile($filename){        $contents =$this->GetFile();        $fp =fopen($filename,'w');        fwrite($fp,$contents);        fclose($fp);    }     function GetMimeType($filename){        $pathinfo =pathinfo($filename);        switch ($pathinfo['extension']) {            case 'htm':$mimetype ='text/html';break;            case 'html':$mimetype ='text/html';break;            case 'txt':$mimetype ='text/plain';break;            case 'cgi':$mimetype ='text/plain';break;            case 'php':$mimetype ='text/plain';break;            case 'css':$mimetype ='text/css';break;            case 'jpg':$mimetype ='image/jpeg';break;            case 'jpeg':$mimetype ='image/jpeg';break;            case 'jpe':$mimetype ='image/jpeg';break;            case 'gif':$mimetype ='image/gif';break;            case 'png':$mimetype ='image/png';break;            default:$mimetype ='application/octet-stream';break;        }        return $mimetype;    }}?>


2. write word comments in pure HTML format: the disadvantage of this method is that it does not support batch download, because a page can only have one header, (no matter whether it is used remotely or locally, only one header can be output on the declaration header page.) even if you generate the statement cyclically, only one word is generated. (of course, you can modify the preceding method to implement the statement)

Principle:

Use ob_start to store html pages first (multiple headers can be generated in batches to solve the problem), and then use

Code:

 ';}function save($path){ echo "";$data = ob_get_contents();ob_end_clean(); $this->wirtefile ($path,$data);} function wirtefile ($fn,$data){$fp=fopen($fn,"wb");fwrite($fp,$data);fclose($fp);}}
$ Html ='
 
 
PHP10086 #;/A>
PHP10086 #;/A>
PHP10086
The most reliable PHP technology blog sharing website
'; // Generate for ($ I = 1; $ I <= 3; $ I ++) {$ word = new word (); $ word-> start (); // $ html = "aaa ". $ I; $ wordname = 'php Huaibei's personal website --PHP10086.com '. $ I. ". doc "; echo $ html; $ word-> save ($ wordname); ob_flush (); // refresh cache flush () before each execution ();}

The above is a detailed description of the sample code in three methods of generating word in PHP. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.