search
HomeBackend DevelopmentPHP TutorialPHP把网页保存为word文件的三种方法_PHP

一、PHP生成word的两种思路或原理

1.利用windows下面的 com组件
2.利用PHP将内容写入doc文件之中
具体实现方法如下。

二、利用windows下面的com组件

原理:com作为PHP的一个扩展类,安装过office的服务器会自动调用word.application的com,可以自动生成文档,PHP官方文档手册:http://www.php.net/manual/en/class.com.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;
?>
个人建议:com实例后的方法都需要查找官方文档才知道什么意思,编辑器没有代码提示,非常不方便,另外这个效率也不是很高,不推荐使用

三、利用PHP将内容写入doc文件之中
这个方法又可以分为两种方法

1.生成mht格式(和HTML很相似)写入word
2.纯HTML格式写入word


1)、生成mht格式(和HTML很相似)写入word

复制代码 代码如下:/**
 * 根据HTML代码获取word文档内容
 * 创建一个本质为mht的文档,该函数会分析文件内容并从远程下载页面中的图片资源
 * 该函数依赖于类MhtFileMaker
 * 该函数会分析img标签,提取src的属性值。但是,src的属性值必须被引号包围,否则不能提取
 *
 * @param string $content HTML内容
 * @param string $absolutePath 网页的绝对路径。如果HTML内容里的图片路径为相对路径,那么就需要填写这个参数,来让该函数自动填补成绝对路径。这个参数最后需要以/结束
 * @param bool $isEraseLink 是否去掉HTML内容中的链接
 */
function getWordDocument( $content , $absolutePath = "" , $isEraseLink = true )
{
    $mht = new MhtFileMaker();
    if ($isEraseLink)
        $content = preg_replace('/(\s*.*?\s*)/i' , '$1' , $content);   //去掉链接

    $images = array();
    $files = array();
    $matches = array();
    //这个算法要求src后的属性值必须使用引号括起来
    if ( preg_match_all('/PHP把网页保存为word文件的三种方法_PHP/i',$content ,$matches ) )
    {
        $arrPath = $matches[1];
        for ( $i=0;$i        {
            $path = $arrPath[$i];
            $imgPath = trim( $path );
            if ( $imgPath != "" )
            {
                $files[] = $imgPath;
                if( substr($imgPath,0,7) == 'http://')
                {
                    //绝对链接,不加前缀
                }
                else
                {
                    $imgPath = $absolutePath.$imgPath;
                }
                $images[] = $imgPath;
            }
        }
    }
    $mht->AddContents("tmp.html",$mht->GetMimeType("tmp.html"),$content);

    for ( $i=0;$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!
";
        }
    }

    return $mht->GetFile();
}

这个函数的主要功能其实就是分析HTML代码中的所有图片地址,并且依次下载下来。获取到了图片的内容以后,调用MhtFileMaker类,将图片添加到mht文件中。具体的添加细节,封装在MhtFileMaker类中了。

使用方法1:远程调用
复制代码 代码如下:$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);
其中,$content变量应该是HTML源代码,后面的链接应该是能填补HTML代码中图片相对路径的URL地址


其中,$content变量应该是HTML源代码,后面的链接应该是能填补HTML代码中图片相对路径的URL地址

使用方法2:本地生成调用
复制代码 代码如下:
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
$wordStr = 'PHP教程网站--bitsCN.com';
$fileContent = getWordDocument($wordStr);
$fileName = iconv("utf-8", "GBK", ‘PHP教程' . '_'. $intro . '_' . rand(100, 999));  
header("Content-Type: application/doc");
header("Content-Disposition: attachment; filename=" . $fileName . ".doc");
echo $fileContent;

注意,在使用这个函数之前,您需要先包含类MhtFileMaker,这个类可以帮助我们生成Mht文档。

复制代码 代码如下:/***********************************************************************
Class:        Mht File Maker
Version:      1.2 beta
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;
    }

    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;
    }
}
?>

点评:这种方法的缺点是不支持批量生成下载,因为一个页面只能有一个header,(无论远程使用还是本地生成声明header页面只能输出一个header),即使你循环生成,结果还是只有一个word生成(当然你可以修改上面的方式来实现)

2.纯HTML格式写入word

原理:

利用ob_start把html页面先存储起来(解决一下页面多个header问题,可以批量生成),然后在写入doc文档内容利用

代码:
复制代码 代码如下:class word
{
    function start()
    {
        ob_start();
        echo '        xmlns:w="urn:schemas-microsoft-com:office:word"
        xmlns="http://www.w3.org/TR/REC-html40">';
    }
    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.bitsCN.com
PHP10086 http://www.bitsCN.com

  PHP10086

  最靠谱的PHP技术分享网站
  PHP把网页保存为word文件的三种方法_PHP
  

';

//批量生成
for($i=1;$i    $word = new word();
    $word->start();
    //$html = "aaa".$i;
    $wordname = 'PHP教程网站--bitsCN.com'.$i.".doc";
    echo $html;
    $word->save($wordname);
    ob_flush();//每次执行前刷新缓存
    flush();
}
个人点评:这种方法效果最好,原因有三个:

第一代码比较简洁,很容易理解
第二是支持批量生成word(这个很重要)
第三是支持完整的html代码

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
网页打不开是什么原因网页打不开是什么原因Jun 26, 2023 am 11:49 AM

网页打不开的原因有:1、电脑的本地连接被禁用;2、拨号上网帐号与密码输入不正确;3、路由器故障或路由器设置出现问题;4、由DNS错误导致的IE打不开网页;5、hosts文件被修改导致的IE打不开网页;6、IP地址设置错误或者获取失败导致IE打不开网页。

使用JavaScript开发网页投票系统使用JavaScript开发网页投票系统Aug 09, 2023 pm 01:30 PM

使用JavaScript开发网页投票系统摘要:随着互联网的飞速发展,网上投票成为了一种方便快捷的方式,用于收集公众的意见和做出决策。本文将介绍使用JavaScript开发一个简单的网页投票系统,实现了用户可以选择选项并提交投票的功能。介绍:网页投票系统是一个在网页上显示多个选项并允许用户选择的程序。它可以用于许多场景,例如选举投票、产品调查、意见收集等。本文

网页无法访问怎么办网页无法访问怎么办Sep 06, 2023 am 09:36 AM

网页无法访问的解决办法有检查网络连接、清除浏览器缓存、检查网页地址、尝试使用其他浏览器、检查服务器状态、检查域名解析、检查防火墙和安全设置和联系网站管理员等。详细介绍:1、检查网络连接,确保网络连接正常,可以尝试打开其他网页或者使用其他设备进行访问,确定是否是网络连接问题,如果其他网页可以正常访问,那么可能是该网页的问题;2、清除浏览器缓存,浏览器缓存可能导致网页无法加载等等。

网页打开慢解决方法网页打开慢解决方法Aug 17, 2023 am 10:53 AM

网页打开慢解决方法:1、检查网络连接速度,可以使用在线测速工具来测试网络,可以联系网络服务提供商解决问题;2、可以通过清理浏览器缓存来改善网页打开速度,可以在浏览器的设置中找到清除缓存的选项,并选择清除所有缓存数据;3、在浏览器的插件和扩展程序管理页面,可以尝试禁用浏览器插件和扩展程序;4、网页打开慢还可能与电脑的性能有关,关闭占用系统资源的程序或进程也可以提高网页加载速度。

拥有自我意识的AI:AutoGPT拥有自我意识的AI:AutoGPTMay 25, 2023 am 10:28 AM

1、引言ChatGPT在当下已经风靡一时,作为自然语言处理模型的佼佼者,ChatGPT的优势在于其能够生成流畅、连贯的对话,同时还能够理解上下文并根据上下文进行回答。针对不同的应用场景可以进行快速定制,例如,在客服、教育、娱乐等领域中,ChatGPT可以作为智能助手为用户提供便捷的服务和娱乐体验。从GPT-3到GPT-4,我们可以看到在高级推理,输入设置,微调行为和理解更长的上下文信息等方面,ChatGPT在不断的优化训练中已经取得了显著的进展。但是针对于这种交互式的GPT模型,我们更希望看到能

JavaScript 如何实现网页自动轮播功能?JavaScript 如何实现网页自动轮播功能?Oct 16, 2023 am 09:25 AM

JavaScript如何实现网页自动轮播功能?随着互联网的普及,网页的设计和展示方式也越来越丰富多样。其中,网页自动轮播功能成为了许多网站及应用中常见的元素之一。本文将介绍如何使用JavaScript实现网页自动轮播功能,并提供具体的代码示例。一、HTML结构在实现自动轮播功能之前,首先需要确定网页的HTML结构。一般来说,自动轮播功能常使用图片或其他内

win10网络被禁用了怎么打开网页win10网络被禁用了怎么打开网页Jun 29, 2023 pm 05:37 PM

win10网络被禁用了怎么打开网页?使用win10系统的时候,发现网络被禁用了,就没有办法使用电脑,这种情况应该如何解决。很多小伙伴不知道怎么操作,小编下面整理了windows10网络被禁用了恢复教程,如果你感兴趣的话,跟着小编一起往下看看吧!win10网络被禁用了怎么打开1、在状态栏右边找到网络连接图标之后,右键点击它,然后选择“打开网络和Internet设置”选项并点击2、打开之后在出现的界面右边,找到并点击打开网络和共享中心3、点击更改适配器设置这个选项,找到被禁用的网络,右键点击它4、选

如虎添翼,六个让你效率翻倍的ChatGPT插件如虎添翼,六个让你效率翻倍的ChatGPT插件May 17, 2023 pm 02:28 PM

ChatGPT是一个超强的AI应用程序,OpenAI已经发布的GPT-4引起了更广泛的关注。ChatGPT是由OpenAI开发的专门从事对话的AI聊天机器人,其主要目标是使AI系统更自然地进行互动。大家可能都已经尝试过ChatGPT,今天讲一讲与这个全新工具互动的不同方法。本文总结了6个可以使ChatGPT成为日常助手(甚至超越日常助手)的工具!1.【GoogleChromeExtension】在任何地方使用ChatGPT想在任何地方轻松地使用ChatGPT吗?那么你可以使用Chrome插件(h

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools