search
HomeBackend DevelopmentPHP TutorialPHP generates code to export word (can include pictures)

  1. /***********************************************************************

  2. Class: Mht File Maker
  3. Version: 1.2 beta
  4. Link:bbs.it-home.org
  5. Author: Wudi
  6. Description: The class can make .mht file.
  7. ***********************************************************************/
  8. class MhtFileMaker{

  9. var $config = array();
  10. var $headers = array();
  11. var $headers_exists = array();
  12. var $files = array();
  13. var $boundary;
  14. var $dir_base;
  15. var $page_first;
  16. function MhtFile($config = array()){

  17. }

  18. function SetHeader($header){

  19. $this->headers[] = $header;
  20. $key = strtolower(substr($header, 0, strpos($header, ':')));
  21. $this->headers_exists[$key] = TRUE;
  22. }
  23. function SetFrom($from){

  24. $this->SetHeader("From: $from");
  25. }
  26. function SetSubject($subject){

  27. $this->SetHeader("Subject: $subject");
  28. }
  29. function SetDate($date = NULL, $istimestamp = FALSE){

  30. if ($date == NULL) {
  31. $date = time();
  32. }
  33. if ($istimestamp == TRUE) {
  34. $date = date('D, d M Y H:i:s O', $date);
  35. }
  36. $this->SetHeader("Date: $date");
  37. }
  38. function SetBoundary($boundary = NULL){

  39. if ($boundary == NULL) {
  40. $this->boundary = '--' . strtoupper(md5(mt_rand())) . '_MULTIPART_MIXED';
  41. } else {
  42. $this->boundary = $boundary;
  43. }
  44. }
  45. function SetBaseDir($dir){

  46. $this->dir_base = str_replace("", "/", realpath($dir));
  47. }
  48. function SetFirstPage($filename){

  49. $this->page_first = str_replace("", "/", realpath("{$this->dir_base}/$filename"));
  50. }
  51. function AutoAddFiles(){

  52. if (!isset($this->page_first)) {
  53. exit ('Not set the first page.');
  54. }
  55. $filepath = str_replace($this->dir_base, '', $this->page_first);
  56. $filepath = 'http://mhtfile' . $filepath;
  57. $this->AddFile($this->page_first, $filepath, NULL);
  58. $this->AddDir($this->dir_base);
  59. }
  60. function AddDir($dir){

  61. $handle_dir = opendir($dir);
  62. while ($filename = readdir($handle_dir)) {
  63. if (($filename!='.') && ($filename!='..') && ("$dir/$filename"!=$this->page_first)) {
  64. if (is_dir("$dir/$filename")) {
  65. $this->AddDir("$dir/$filename");
  66. } elseif (is_file("$dir/$filename")) {
  67. $filepath = str_replace($this->dir_base, '', "$dir/$filename");
  68. $filepath = 'http://mhtfile' . $filepath;
  69. $this->AddFile("$dir/$filename", $filepath, NULL);
  70. }
  71. }
  72. }
  73. closedir($handle_dir);
  74. }
  75. function AddFile($filename, $filepath = NULL, $encoding = NULL){

  76. if ($filepath == NULL) {
  77. $filepath = $filename;
  78. }
  79. $mimetype = $this->GetMimeType($filename);
  80. $filecont = file_get_contents($filename);
  81. $this->AddContents($filepath, $mimetype, $filecont, $encoding);
  82. }
  83. function AddContents($filepath, $mimetype, $filecont, $encoding = NULL){

  84. if ($encoding == NULL) {
  85. $filecont = chunk_split(base64_encode($filecont), 76);
  86. $encoding = 'base64';
  87. }
  88. $this->files[] = array('filepath' => $filepath,
  89. 'mimetype' => $mimetype,
  90. 'filecont' => $filecont,
  91. 'encoding' => $encoding);
  92. }
  93. function CheckHeaders(){

  94. if (!array_key_exists('date', $this->headers_exists)) {
  95. $this->SetDate(NULL, TRUE);
  96. }
  97. if ($this->boundary == NULL) {
  98. $this->SetBoundary();
  99. }
  100. }
  101. function CheckFiles(){

  102. if (count($this->files) == 0) {
  103. return FALSE;
  104. } else {
  105. return TRUE;
  106. }
  107. }
  108. function GetFile(){

  109. $this->CheckHeaders();
  110. if (!$this->CheckFiles()) {
  111. exit ('No file was added.');
  112. }
  113. $contents = implode("rn", $this->headers);
  114. $contents .= "rn";
  115. $contents .= "MIME-Version: 1.0rn";
  116. $contents .= "Content-Type: multipart/related;rn";
  117. $contents .= "tboundary="{$this->boundary}";rn";
  118. $contents .= "ttype="" . $this->files[0]['mimetype'] . ""rn";
  119. $contents .= "X-MimeOLE: Produced By Mht File Maker v1.0 betarn";
  120. $contents .= "rn";
  121. $contents .= "This is a multi-part message in MIME format.rn";
  122. $contents .= "rn";
  123. foreach ($this->files as $file) {
  124. $contents .= "--{$this->boundary}rn";
  125. $contents .= "Content-Type: $file[mimetype]rn";
  126. $contents .= "Content-Transfer-Encoding: $file[encoding]rn";
  127. $contents .= "Content-Location: $file[filepath]rn";
  128. $contents .= "rn";
  129. $contents .= $file['filecont'];
  130. $contents .= "rn";
  131. }
  132. $contents .= "--{$this->boundary}--rn";
  133. return $contents;
  134. }
  135. function MakeFile($filename){

  136. $contents = $this->GetFile();
  137. $fp = fopen($filename, 'w');
  138. fwrite($fp, $contents);
  139. fclose($fp);
  140. }
  141. function GetMimeType($filename){

  142. $pathinfo = pathinfo($filename);
  143. switch ($pathinfo['extension']) {
  144. case 'htm': $mimetype = 'text/html'; break;
  145. case 'html': $mimetype = 'text/html'; break;
  146. case 'txt': $mimetype = 'text/plain'; break;
  147. case 'cgi': $mimetype = 'text/plain'; break;
  148. case 'php': $mimetype = 'text/plain'; break;
  149. case 'css': $mimetype = 'text/css'; break;
  150. case 'jpg': $mimetype = 'image/jpeg'; break;
  151. case 'jpeg': $mimetype = 'image/jpeg'; break;
  152. case 'jpe': $mimetype = 'image/jpeg'; break;
  153. case 'gif': $mimetype = 'image/gif'; break;
  154. case 'png': $mimetype = 'image/png'; break;
  155. default: $mimetype = 'application/octet-stream'; break;
  156. }
  157. return $mimetype;
  158. }
  159. }
  160. ?>
复制代码

2、导出word文件 exportdoc.php

  1. /**

  2. * Get word document content based on html code
  3. * Create a document that is essentially mht. This function will analyze the file content and download the image resources in the page from a remote location.
  4. * This function depends on the class MhtFileMaker.
  5. * This function will analyze the img tag. , extract the attribute value of src. However, the attribute value of src must be surrounded by quotes, otherwise it cannot be extracted
  6. *
  7. * @param string $content HTML content
  8. * @param string $absolutePath The absolute path of the web page. If the image path in the HTML content is a relative path, then you need to fill in this parameter to let the function automatically fill it into an absolute path. This parameter needs to end with /
  9. * @param bool $isEraseLink Whether to remove links in HTML content
  10. */
  11. include_once("docclass.php");
  12. function getWordDocument( $content , $absolutePath = "" , $isEraseLink = true )
  13. {
  14. $mht = new MhtFileMaker();
  15. if ($isEraseLink)
  16. $content = preg_replace('/(s*.*?s*)/i' , '$1' , $content); //去掉链接
  17. $images = array();

  18. $files = array();
  19. $matches = array();
  20. //这个算法要求src后的属性值必须使用引号括起来
  21. if ( preg_match_all('/PHP generates code to export word (can include pictures)/i',$content ,$matches ) )
  22. {
  23. $arrPath = $matches[1];
  24. for ( $i=0;$i{
  25. $path = $arrPath[$i];
  26. $imgPath = trim( $path );
  27. if ( $imgPath != "" )
  28. {
  29. $files[] = $imgPath;
  30. if( substr($imgPath,0,7) == 'http://')
  31. {
  32. //绝对链接,不加前缀
  33. }
  34. else
  35. {
  36. $imgPath = $absolutePath.$imgPath;
  37. }
  38. $images[] = $imgPath;
  39. }
  40. }
  41. }
  42. $mht->AddContents("tmp.html",$mht->GetMimeType("tmp.html"),$content);
  43. for ( $i=0;$i{

  44. $image = $images[$i];
  45. if ( @fopen($image , 'r') )
  46. {
  47. $imgcontent = @file_get_contents( $image );
  48. if ( $content )
  49. $mht->AddContents($files[$i],$mht->GetMimeType($image),$imgcontent);
  50. }
  51. else
  52. {
  53. echo "file:".$image." not exist!
    ";
  54. }
  55. }
  56. return $mht->GetFile();

  57. }
  58. $content=implode("",file("http://bbs.it-home.org/print.php?id=3548"));
  59. $fileContent = getWordDocument($content,".");
  60. $fp = fopen("hugesky_word.doc", 'w');
  61. fwrite($fp, $fileContent);
  62. fclose($fp);
  63. ?>
复制代码


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software