Three ways to generate Word documents in PHP

Source: Internet
Author: User
Three ways in which PHP generates word

How PHP generates Word

Take advantage of COM components under Windows

Use PHP to write content to a doc file

PHP generates word specific implementations:

Take advantage of COM components under Windows

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

Use official examples:

 
  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 document to know what meaning, the editor does not have the code hint, very inconvenient, moreover this efficiency is not very high, not recommended to use

Use PHP to write content to a doc file

This method can be divided into two methods

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 a document that is essentially mht that parses the contents of a file and downloads the picture resource from the page remotely * The function relies on the class Mhtfilemaker * The function parses the IMG tag and extracts the SRC attribute value. However, the attribute value of SRC must be enclosed in quotation marks, otherwise it cannot extract * * @param string $content HTML content * @param string $absolutePath Absolute path to the Web page. If the image path in the HTML content is a relative path, you need to fill in this parameter to let the function automatically fill in the absolute path. This parameter ends with a/end * @param bool $isEraseLink Whether to remove the link in the HTML content */function getworddocument ($content, $absolutePath = "", $isEras    Elink = True) {$mht = new mhtfilemaker ();   if ($isEraseLink) $content = Preg_replace ('/(\s*.*?\s*) <\/a>/i ', ' $ ', $content);    Remove link $images = Array ();    $files = Array ();    $matches = Array ();        This algorithm requires that the attribute value 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 ();}

The main function of this function is to parse all the image addresses in the HTML code and download them sequentially. After getting the contents of the picture, call the Mhtfilemaker class and add the picture to the MHT file. Specific add-on details, encapsulated in the Mhtfilemaker class.

How to use: Remote Call

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);

Where the $content variable should be the HTML source code, the following link should be able to fill the HTML code in the image relative to the path of the URL address

Local Build Call:

Header ("Cache-control:no-cache, must-revalidate"); Header ("Pragma:no-cache"); $wordStr = ' php huaibei personal website--php10086.com ' ; $fileContent = Getworddocument ($wordStr); $fileName = Iconv ("Utf-8", "GBK", "PHP Huaibei". '_'. $intro. '_' . RAND (999));  Header ("Content-type:application/doc"); header ("Content-disposition:attachment; Filename= ". $fileName. ". Doc"); Echo $fileContent;

Note that before using this function, you need to include the class Mhtfilemaker, which can help us generate the MHT document.

 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) {$fi        Lepath = $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 ' and $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 was 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 '; 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 to Word in plain HTML format

Principle:

Use Ob_start to store HTML pages first (solve multiple header problems on the page, you can generate batches), and then write the doc document content using

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 Http://www.php10086.com
PHP10086 Http://www.php10086.com
PHP10086
The most reliable PHP technology blog share site
'; Batch build for ($i =1; $i <=3; $i + +) {$word = new word (); $word->start (); $html = "AAA". $i; $wordname = ' php Huaibei's personal site--php10086.com '. $i. ". Doc "; Echo $html; $word->save ($wordname); Ob_flush ();//flush Cache flush () before each execution;}

Personal Comments : This method works best for two reasons:

The first code is relatively concise, easy to understand, the second support batch generation of Word (this is important)

Third, full HTML code support

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

  • 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.