Three ways to implement PHP to generate Word documents _php instance

Source: Internet
Author: User
Tags flush php class xmlns

Recent work encountered questions about building word

Now summarize the three ways to build word.

BTW: It seems that as long as the title with PHP is not a seemingly high number of clicks (Brother my title or with PHP), do not know why, the estimated blog Park on the net technology Daniel More, if the java,.net,php to the programmer's girlfriend, Then Java is a lady under Oracle,. Net Microsoft's Noble, PHP is the root of the mountain village wild aunt, this let me and so on php grass people stuffy male love why is the situation so worthy. The whining is over, so write it.

PHP generates Word principle

    • Take advantage of the COM components under Windows
    • Use PHP to write content to doc files

Specific implementation:

Take advantage of the COM components under Windows

Principle: com as an extension of PHP class, the server installed Office will automatically call Word.Application com, can automatically generate documents, PHP official documentation manual: Http://www.php.net/manual/en/class.com.php

Use official examples:

<?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 advice: COM instance after the method will need to find the official document to know what meaning, the editor does not have code hints, very inconvenient, and this efficiency is not very high, do not recommend the use

Use PHP to write content to doc files

This method can be divided into two different ways

    • Generate MHT format (very similar to HTML) to write to Word
    • Write to Word in plain HTML format

Generate MHT format (very similar to HTML) to write to Word

/** * Get Word document content based on HTML code * Create an essentially MHT document that analyzes the contents of the file and downloads the picture resource from the remote download page * The function relies on the class Mhtfilemaker * The function analyzes the IMG tag to extract the attribute values of SRC. However, the attribute value of SRC must be enclosed in quotation marks, otherwise the * * @param string $content HTML content * @param string $absolutePath The absolute path of the Web page cannot be extracted. If the image path in the HTML content is a relative path, then you need to fill in the parameter to make the function automatically fill the absolute path. This parameter needs to end with/end * @param bool $isEraseLink Whether to remove the link in HTML content/function Getworddocument ($content, $absolutePath = "", $isE
 Raselink = True) {$mht = new mhtfilemaker (); if ($isEraseLink) $content = Preg_replace ('/<a\s*.*?\s*> (\s*.*?\s*) <\/a>/i ', ' $ ', $content);
 Remove the link $images = Array ();
 $files = Array ();
 $matches = Array (); This algorithm requires that the attribute value after SRC must be enclosed in quotes 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, 0,7) = = ' 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 sequentially. After you get the contents of the picture, call the Mhtfilemaker class and add the picture to the MHT file. Details are added, encapsulated in the Mhtfilemaker class.

How to: Remotely invoke

Url= http://www.***.com;
 
$content = file_get_contents ($url);
 
$fileContent = Getworddocument ($content, "http://www.jb51.net/Music/etc/");
$fp = fopen ("Test.doc", ' W ');
Fwrite ($fp, $fileContent);
Fclose ($FP);

Where the $content variable should be HTML source code, and the following link should be a URL that fills the relative path of the picture in the HTML code.

Local Build Call:

Header ("Cache-control:no-cache, must-revalidate"); 
Header ("Pragma:no-cache"); 
$wordStr = ' http://www.jb51.net/'; 
$fileContent = Getworddocument ($WORDSTR); 
$fileName = Iconv ("Utf-8", "GBK", ' jb51 '. '_'. $intro. '_' . RAND (999)); 
Header ("Content-type:application/doc"); 
Header ("content-disposition:attachment; Filename= ". $fileName. ". Doc"); 
Echo $fileContent;

Note that before you use this function, you need to include class Mhtfilemaker, which can help us generate MHT documents.

<?php/*********************************************************************** class:mht File Maker version:1.2 b
ETA date:02/11/2007 Author: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;
 The 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"); The function setboundary ($boundary = null) {if ($boundary = = null) {$this->boundary = '-'. Strtoupper (MD5 Mt_r and ()).
  ' _multipart_mixed ';
  else {$this->boundary = $boundary;
 The function Setbasedir ($dir) {$this->dir_base = str_replace ("\", "/", Realpath ($dir)); The function Setfirstpage ($filename) {$this->page_first = str_replace ("\", "/", Realpath ("{$this->dir_base}/$fil
 Ename "));
  The function autoaddfiles () {if (!isset ($this->page_first)) {exit (' not set the ' the '. ');
  $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);
  The function Adddir ($dir) {$handle _dir = Opendir ($dir); while ($filename = Readdir ($handle _dir)) {if ($filename!= '. ') && ($filename!= ' ... ') && ("$dir/$filenam E "!= $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 = ch
   Unk_split (Base64_encode ($filecont), 76);
  $encoding = ' base64 '; $this->files[] = array (' filepath ' => $filepath, ' mimetype ' => $mimetype, ' Filecont ' => $fi
 Lecont, ' encoding ' => $encoding);
 
 }function Checkheaders () {if (!array_key_exists (' Date ', $this->headers_exists)) {$this->setdate (NULL, TRUE);
  } if ($this->boundary = = NULL) {$this->setboundary ();
  The function checkfiles () {if (count ($this->files) = = 0) {return FALSE;
  else {return TRUE;
  }} function GetFile () {$this->checkheaders ();
  if (! $this->checkfiles ()) {exit (' No file is 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;
  The function MakeFile ($filename) {$contents = $this->getfile ();
  $fp = fopen ($filename, ' w ');
  Fwrite ($fp, $contents);
 Fclose ($FP);
  The function GetMimeType ($filename) {$pathinfo = PathInfo ($filename);
   Switch ($pathinfo [' extension ']) {case ' htm ': $mimetype = ' text/html '; 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 build downloads, because a page can only have one header, (whether the remote use or the local build Declaration Header page can only output one header), even if you loop generation, The result is only one word generation (you can, of course, change the way it is implemented)

2. Write to Word in plain HTML format

Principle:

Use Ob_start to store HTML pages first (solve multiple header problems on a page, can be generated in batches), and then write doc content to use

Code:

<?php
class word
{ 
function start ()
{
ob_start ();
Echo '  
 

Personal Comment: This method works best, for two reasons:

The first code is simpler and easier to understand, and the second supports batch generation of Word (this is important)

The third supports complete HTML code

Generated three Word documents: and the content supports full HTML code display, the third method strongly recommends

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat 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.