PHP generates Word documents in three ways,

Source: Internet
Author: User

PHP generates Word documents in three ways,

Recently encountered a problem about word generation.

Now we will summarize the three methods for generating word.

Btw: It seems that as long as the title is PHP, it seems that the clicks are not very high (my brother, my title is still PHP). I don't know why. It is estimated that there are many net technical experts in the blog Park, if java ,. net, php is like a programmer's girlfriend, so java is a big show under the Oracle door ,. net Microsoft's name family, PHP is under the grass-roots village wild Gu, which makes me wait for PHP grass and the masses to smother male feeling why it is so embarrassing .. The complaint is over. Write it officially.

How PHP generates word

  • Use com components in windows
  • Use PHP to write content into the doc file

Specific implementation:

Use com components in windows

Principle: com as a PHP extension class, installed on the office server will automatically call the word. application of com, can automatically generate documents, PHP official documentation Manual: http://www.php.net/manual/en/class.com.php

Use official instances:

<?php// starting word$word = new COM("word.application") or die("Unable to instantiate Word");echo "Loaded Word, version {$word->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.

Use PHP to write content into the doc file

This method can be divided into two methods.

  • Generate mht format (similar to HTML) and write it to word
  • Write word in pure HTML Format

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 ('/<a \ s *. *? \ S *> (\ 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 <count ($ arrPath ); $ I ++) {$ path = $ arrPath [$ I]; $ imgPath = trim ($ path); if ($ imgPath! = "") {$ Files [] = $ imgPath; if (substr ($ imgPath,) = 'HTTP: // ') {// absolute link, without prefix} else {$ imgPath = $ absolutePath. $ imgPath ;}$ images [] = $ imgPath ;}}$ mht-> AddContents ("tmp.html", $ mht-> GetMimeType ("tmp.html"), $ content ); for ($ I = 0; $ I <count ($ images); $ I ++) {$ image = $ images [$ I]; if (@ fopen ($ image, 'R') {$ imgcontent = @ file_get_contents ($ image); if ($ content) $ mht-> AddContents ($ files [$ I], $ mht-> GetMimeType ($ image), $ imgcontent);} else {echo "file:". $ image. "not exist! <Br/> ";}}return $ mht-> GetFile ();}

The main function of 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.

Usage: Remote Call

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

Among them, the $ content Variable should be the HTML source code, and the link below should be the URL address that can fill the relative path of the image in the HTML code

Locally generated call:

header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); $wordStr = 'http://www.bkjia.com/'; $fileContent = getWordDocument($wordStr); $fileName = iconv("utf-8", "GBK", ‘jb51' . '_'. $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.

<?php/***********************************************************************Class:  Mht File MakerVersion:  1.2 betaDate:   02/11/2007Author:  Wudi 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->files as $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; }}?>

Comment: 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 generated to generate a declaration header page, only one header can be output ), even if you generate the result cyclically, only one word is generated (you can modify the above method to implement it)

2. Write word in pure HTML Format

Principle:

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

Code:

<?phpclass word{ function start(){ob_start();echo '
$ Html = '<table width = 600 cellpadding = "6" cellspacing = "1" bgcolor = "#336699"> <tr bgcolor = "White"> <td> PHP10086 </ td> <a href = "http://www.php10086.com" target = "_ blank"> http://www.php10086.com </a> </td> </tr> <tr bgcolor = "red"> <td> PHP10086 </td> <a href = "http://www.php10086.com" target = "_ blank"> http://www.php10086.com </a> </td> </tr> <tr bgcolor = "White"> <td colspan = 2> PHP10086 <br> the most reliable PHP Technology blog sharing site  </td> </tr> </table> '; // 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 ();}

Personal comment: This method works best for two reasons:

The first code is concise and easy to understand. The second method supports batch generation of word (this is very important)

Third, complete html code is supported.

Three Word documents are generated, and the complete html code is displayed. The third method is strongly recommended.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.