show doc,docx文件内容php

时间:2016-06-07 03:26:35

标签: php laravel-5 phpword

我在docx中显示内容或php(laravel 5)文件时遇到问题 我没有找到任何显示内容的解决方案。我使用phpword lib进行阅读,我阅读了phpword的文档但没有找到解决方案 这是我的代码:
+上传html:

<form method="post" action="doc/upload" enctype="multipart/form-data">
            {{csrf_field()}}
            <input type="file" name="file" accept=".doc, .docx"/>

            <button class="btn btn-primary" style="margin-top: 5px"><span class="glyphicon glyphicon-import" aria-hidden="true"></span> Upload</button>
        </form>

+进程:

public function upload(Request $request){
    $file = $request->file('file');
    $phpWord = \PhpOffice\PhpWord\IOFactory::load($file);
    //i use this line below for showing but it can not show exactly 
    $phpWord->save('php://output');
}

+结果:
enter image description here

3 个答案:

答案 0 :(得分:3)

我也在寻找答案,这是我使用PHPWord读取docx文件的代码。我正在完成安装步骤(这是针对laravel 5)

步骤1.在作曲家文件中添加https://github.com/PHPOffice/PHPWord。 (composer.json)

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

步骤2.将IOFactory添加到您的控制器。

use PhpOffice\PhpWord\IOFactory;

步骤3.创建一个阅读器并加载文件。

$phpWord = IOFactory::createReader('Word2007')->load($request->file('file')->path());

步骤4.您已经可以检查$ phpWord中的文档属性和内容。

步骤5.如果要提取文档的内容。使用下面的代码

$phpWord = IOFactory::createReader('Word2007')->load($request->file('file')->path());

foreach($phpWord->getSections() as $section) {
            foreach($section->getElements() as $element) {
                if(method_exists($element,'getText')) {
                    echo($element->getText() . "<br>");
                }
            }
        }

答案 1 :(得分:2)

如果你想显示所有单词doc contens,那么最好的方法是将word文件保存为html,然后在iframe中显示html内容。

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
$objWriter->save('doc.html');

如果你只想从文档中获取纯文本内容,你可以尝试这样的东西

foreach($phpWord->getSections() as $section) {
    foreach($section->getElements() as $element) {
        if(method_exists($element,'getText')) {
            echo($element->getText() . "<br>");
        }
    }
}

希望这有帮助。

答案 2 :(得分:1)

对于那些正在寻找将 Microsoft Word 文档转换为纯文本的更简单(在我的情况下更准确)方法的人,我建议您查看此处找到的此主题:How to extract text from word file .doc,docx,.xlsx,.pptx php< /p>