php利用phpword读取word

1. 本次案例使用的phpword版本0.17.0

1.下载phpword

创建composer.json文件,内容如下,然后找到项目文件夹,cmd执行命令:composer install 下载文件

{
    "require": {
       "phpoffice/phpword": "v0.17.*"
    }
}

 

2.phpword 重要名词解释

section(部分) : phpword中将word文档分为若干个section(部分)

element(元素) : 每个section包含若干个element(元素)、文本、图片,元素分为文本元素、表格元素、其他(未涉及不做讨论)

textRun(文本元素) : 每个文本集合包含多个文本

text(文本) : 为字符或者图片

table(表格元素) : 每个表格元素包含多个行 row

row(行) : 每个行包含多个列 cell

cell(列) : 每个列包含多个textRun(文本元素) 这里没错,就是包含多个文本元素(表格元素也可以但是没人在word表格的某一个格里再来一个表格吧)

 

各个节点之间的关系图

 

 

3.执行代码

<?php
/**
 * Created by PhpStorm.
 * User: chengyanping
 * Date: 2021/5/19
 * Time: 13:14
 */
require_once './vendor/autoload.php';
ini_set('display_errors', true);
ini_set('max_execution_time', '0');
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);

class WordService
{

    public  function importWord($info)
    {
        $word  = self::getWord($info);
//        print_r($word);

        return $word;

    }

    /**
     * 获取word文档内容
     * @param string $path
     * @return array
     */
    public static function getWord($path = '')
    {
        //加载word文档,使用phpword处理
        $phpWord = \PhpOffice\PhpWord\IOFactory::load($path);


//        print_R($phpWord);exit();
        return self::getNodeContent($phpWord);
    }

    /**
     * 根据word主节点获取分节点内容
     * @param $word
     * @return array
     */
    public static function getNodeContent($word)
    {
        $return = [];
        //分解部分
        foreach ($word->getSections() as $section)
        {
            if ($section instanceof \PhpOffice\PhpWord\Element\Section) {
                //分解元素
                foreach ($section->getElements() as $element)
                {



                    //文本元素
                    if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {

                        $text = '';
                        foreach ($element->getElements() as $ele) {
                            $text .= self::getTextNode($ele);
                        }
                        $return[] = $text;
                    }
                    //表格元素
                    else if ($element instanceof \PhpOffice\PhpWord\Element\Table) {
                        foreach ($element->getRows() as $ele)
                        {
                            $return[] = self::getTableNode($ele);
                        }
                    }
                    //保留文本元素
                    else if ($element instanceof \PhpOffice\PhpWord\Element\PreserveText) {

                        //当是预留文本的时候
                        $text='';
                        foreach ($element->getText() as $ele=>$value)
                        {
                            $text .= $value;
                        }
                        $return[] = $text;
                    }
                }
            }
        }
        return $return;
    }

    /**
     * 获取文档节点内容
     * @param $node
     * @return string
     */
    public static function getTextNode($node)
    {
        $return = '';
        //处理文本
        if ($node instanceof \PhpOffice\PhpWord\Element\Text)
        {
            $return .= $node->getText();
        }
        //处理图片
        else if ($node instanceof \PhpOffice\PhpWord\Element\Image)
        {
            $return .= self::pic2text($node);
        }
        //处理文本元素
        else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($node->getElements() as $ele) {
                $return .= self::getTextNode($ele);
            }
        }//处理保留文本
        else if ($node instanceof \PhpOffice\PhpWord\Element\PreserveText) {
            $return .= $node->getText();
        }
        return $return;
    }

    /**
     * 获取表格节点内容
     * @param $node
     * @return string
     */
    public static function getTableNode($node)
    {
        $return = '';
        //处理行
        if ($node instanceof \PhpOffice\PhpWord\Element\Row) {
            foreach ($node->getCells() as $ele)
            {
                $return .= self::getTableNode($ele);
            }
        }
        //处理列
        else if ($node instanceof \PhpOffice\PhpWord\Element\Cell) {
            foreach ($node->getElements() as $ele)
            {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }

    /**
     * 处理word文档中base64格式图片
     * @param $node
     * @return string
     */
    public static function pic2text($node)
    {
        //获取图片编码
        $imageData = $node->getImageStringData(true);
        //添加图片html显示标头
        $imageData = 'data:' . $node->getImageType() . ';base64,' . $imageData;
        $return = '<img src="'.$imageData.'">';
        return $return;
    }
    /**
     * 处理word文档中base64格式图片
     * @param $node
     * @return string
     */
    public static function pic2file($node)
    {
        //图片地址(一般为word文档地址+在word中的锚点位置)
        $imageSrc  = 'images/' . md5($node->getSource()) . '.' . $node->getImageExtension();
        $imageData = $node->getImageStringData(true);
        //将图片保存在本地
        file_put_contents($imageSrc, base64_decode($imageData));
        return $imageSrc;
    }

    /**
     * 将word转化为html(转换存储html文件后展示)
     * @param $path
     * @throws \PhpOffice\PhpWord\Exception\Exception
     */
    public static function word2html($path)
    {
        $phpWord = FileImportService::getOne($path);
        //转为html处理
        $xmlWriter  = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML");
        $path = pathinfo($path);
        $fileName = $path['dirname'] . '/' . $path['filename'] . '.html';
        $xmlWriter->save($fileName);
        $html = file_get_contents($fileName);
        echo $html;
        die;

    }




    public function deleteFile($filePath)
    {
        if (file_exists($filePath)) {
            $tt=unlink($filePath);

            return $tt;
        }
        else {

            return false;
        }

    }


}

 

 

 

参考文献:1.https://github.com/PHPOffice/PHPWord

                   2.https://phpword-zh.readthedocs.io/zh_CN/latest/intro.html

参考文章:https://www.cnblogs.com/haizizhu/p/13808155.html

 

 

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值