検索
ホームページバックエンド開発PHPチュートリアルWeb ページを Word ドキュメントにエクスポートするための PHP コードの紹介

  1. /**
  2. * HTML コードに基づいて Word ドキュメントのコンテンツを取得します
  3. * 本質的に mht であるドキュメントを作成します。この関数はファイルのコンテンツを分析し、リモートの場所からページ内の画像リソースをダウンロードします
  4. * この関数はクラス MhtFileMaker に依存します
  5. *この関数は img タグを解析し、src の属性値を抽出します。ただし、src の属性値は引用符で囲む必要があります。そうしないと抽出できません。
  6. *
  7. * @param string $content HTML コンテンツ
  8. * @param string $absolutePath Web ページの絶対パス。 HTML コンテンツ内の画像パスが相対パスの場合、関数によって絶対パスが自動的に入力されるように、このパラメータを入力する必要があります。このパラメータは / で終わる必要があります
  9. * @param bool $isEraseLink HTML コンテンツ内のリンクを削除するかどうか
  10. */
  11. function getWordDocument( $content , $absolutePath = "" , $isEraseLink = true )
  12. {
  13. $mht = new MhtFileMaker();
  14. if ( $isEraseLink)
  15. $content = preg_replace('/(s*.*?s*)/i' , '$1' , $content);リンクを削除します
  16. $images = array();
  17. $matches = array();
  18. //このアルゴリズムでは、src の後の属性値を引用符で囲む必要があります
  19. if ( preg_match_all(' /< ;img[.n]*?srcs*?=s*?["'](.*?)["'](.*?)/>/i',$content ,$matches ) )
  20. {
  21. $arrPath = $matches[1];
  22. for ( $i=0;$i{
  23. $path = $arrPath[$i];
  24. $imgPath = $path );
  25. if ( $imgPath != "" )
  26. {
  27. $files[] = $imgPath;
  28. if(substr($imgPath,0,7) == 'http://')
  29. / /絶対リンク、プレフィックスなし
  30. }
  31. else
  32. {
  33. $imgPath = $absolutePath.$imgPath;
  34. }
  35. $images[] = $imgPath;
  36. }
  37. }
  38. }
  39. $mht->AddContents("tmp. html ",$mht->GetMimeType("tmp.html"),$content);
  40. for ( $i=0;$i{
  41. $image = $images[ $ i];
  42. if ( @fopen($image , 'r') )
  43. {
  44. $imgcontent = @file_get_contents( $image );
  45. if ( $content )
  46. $mht->AddContents($files[$i] ] ,$mht->GetMimeType($image),$imgcontent);
  47. }
  48. else
  49. {
  50. echo "file:".$image." が存在しません!
    "; return $mht->GetFile();
  51. }
  52. コードをコピー
使用法:

$fileContent = getWordDocument($content,"http://www.yoursite.com/Music/etc/");
$fp = fopen("test.doc", ' w');
    fwrite($fp, $fileContent);
  1. コードをコピーします
  2. このうち、$content 変数は HTML ソース コードである必要があり、次のリンクは HTML コード内の画像の相対パスを埋めることができる URL アドレスである必要があります。 この関数を使用する前に、MhtFileMaker クラスを含める必要があることに注意してください。このクラスは Mht ドキュメントの生成に役立ちます。

    1. /*************************************************** *******************
    2. クラス: Mht File Maker
    3. バージョン: 1.2 ベータ版
    4. リンク: http://bbs.it-home.org
    5. 作者: Wudi
    6. 説明: このクラスは .mht ファイルを作成できます。
    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 = strto lower(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");
    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 ('最初のページを設定しません。');
    54. }
    55. $filepath = str_replace($this->dir_base, '', $this->page_first);
    56. $filepath = 'http://mhtfile' 。 $ファイルパス;
    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' 。 $ファイルパス;
    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. TRUE を返します。
    106. }
    107. }
    108. function GetFile(){
    109. $this->CheckHeaders();
    110. if (!$this->CheckFiles()) {
    111. exit ('ファイルは追加されませんでした。');
    112. }
    113. $contents = implode("rn", $this->headers);
    114. $contents .= "rn";
    115. $contents .= "MIME バージョン: 1.0rn";
    116. $contents .= "Content-Type: multipart/relative;rn";
    117. $contents .= "tboundary="{$this->boundary}";rn";
    118. $contents .= "ttype="" . $this->files[0]['mimetype'] . ""rn";
    119. $contents .= "X-MimeOLE: Mht File Maker v1.0 betarn によって作成";
    120. $contents .= "rn";
    121. $contents .= "これは MIME 形式のマルチパート メッセージです。rn";
    122. $contents .= "rn";
    123. foreach ($this->files as $file) {
    124. $contents .= "--{$this->boundary}rn";
    125. $contents .= "コンテンツ タイプ: $file[mimetype]rn";
    126. $contents .= "コンテンツ転送エンコーディング: $file[encoding]rn";
    127. $contents .= "コンテンツの場所: $file[ファイルパス]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, $fp)
    139. }
    140. 関数 GetMimeType($filename){
    141. $pathinfo($pathinfo['拡張子); ']) {
    142. case 'htm': $mimetype = 'text/html';
    143. case 'html': $mimetype = 'text/プレーン';
    144. ケース 'cgi': $mimetype = 'テキスト/プレーン';
    145. ケース 'テキスト/プレーン'; /css';
    146. case 'jpg': $mimetype = 'image/jpeg';
    147. case 'jpe';画像/jpeg';
    148. ケース 'gif': $mimetype = 'image/gif';壊す;
    149. case 'png': $mimetype = 'image/png';壊す;
    150. デフォルト: $mimetype = 'application/octet-stream';壊す;
    151. }
    152. $mimetype を返します。
    153. }
    154. }
    155. ?>
    156. 复政代
声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
トラフィックの高いウェブサイトのPHPパフォーマンスチューニングトラフィックの高いウェブサイトのPHPパフォーマンスチューニングMay 14, 2025 am 12:13 AM

thesecrettokeepingaphp-poweredwebsterunningsmootlyunderheavyloadinvolvesseveralkeystrategies:1)emform opcodecoduceSciptionexecutiontime、2)aatabasequerycachingwithiThing withiThistolessendavasoload、

PHPでの依存関係注射:初心者向けのコード例PHPでの依存関係注射:初心者向けのコード例May 14, 2025 am 12:08 AM

コードをより明確かつ維持しやすくするため、依存関係が関心(DI)に注意する必要があります。 1)DIは、クラスを切り離すことにより、よりモジュール化されます。2)テストとコードの柔軟性の利便性を向上させ、3)DIコンテナを使用して複雑な依存関係を管理しますが、パフォーマンスの影響と円形の依存関係に注意してください。

PHPパフォーマンス:アプリケーションを最適化することは可能ですか?PHPパフォーマンス:アプリケーションを最適化することは可能ですか?May 14, 2025 am 12:04 AM

はい、最適化されたAphPossibleandessention.1)CachingingusapCutoredatedAtabaseload.2)最適化、効率的なQueries、およびConnectionPooling.3)EnhcodeCodewithBultinctions、Avoididingglobalbariables、およびUsingopcodeching

PHPパフォーマンスの最適化:究極のガイドPHPパフォーマンスの最適化:究極のガイドMay 14, 2025 am 12:02 AM

keyStrategIestsoSificlyvoostphpappliceperformanceare:1)useopcodecachinglikeToreexecutiontime、2)最適化abaseの相互作用とプロペラインデックス、3)3)構成

PHP依存性噴射コンテナ:クイックスタートPHP依存性噴射コンテナ:クイックスタートMay 13, 2025 am 12:11 AM

aphpDependencyInjectionContaineriSATOULTAINATINAGECLASSDEPTINCIES、強化測定性、テスト可能性、および維持可能性。

PHPの依存噴射対サービスロケーターPHPの依存噴射対サービスロケーターMay 13, 2025 am 12:10 AM

SELECT DEPENTENCINGINOFCENT(DI)大規模なアプリケーションの場合、ServicElocatorは小さなプロジェクトまたはプロトタイプに適しています。 1)DIは、コンストラクターインジェクションを通じてコードのテスト可能性とモジュール性を改善します。 2)ServiceLocatorは、センター登録を通じてサービスを取得します。これは便利ですが、コードカップリングの増加につながる可能性があります。

PHPパフォーマンス最適化戦略。PHPパフォーマンス最適化戦略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedforspeedandEfficiencyby:1)enabingopcacheinphp.ini、2)PreparedStatementswithpordatabasequeriesを使用して、3)LoopswithArray_filterandarray_mapfordataprocessing、4)の構成ngincasaSearverseproxy、5)

PHPメールの検証:電子メールが正しく送信されるようにしますPHPメールの検証:電子メールが正しく送信されるようにしますMay 13, 2025 am 12:06 AM

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

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい