Is there a way to read Doc files in PHP similar to Docx?

萝らか妹 提交于 2019-12-08 12:48:31

问题


I am able to extract the text content of a Docx File, I want to do the same for Doc file. I tried using the same code but could not read anything. I guess the reason is "Doc formats are not zipped archives." Here is the code:

  function readDocx ($filePath) 
    {


        // Create new ZIP archive

        $zip = new ZipArchive;
        $dataFile = 'word/document.xml';
        // Open received archive file
        if (true === $zip->open($filePath)) {
            // If done, search for the data file in the archive
            if (($index = $zip->locateName($dataFile)) !== false) {
                // If found, read it to the string
                $data = $zip->getFromIndex($index);
                // Close archive file
                $zip->close();

                // Load XML from a string
                // Skip errors and warnings

                $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);

                $contents = explode('\n',strip_tags($xml->saveXML()));
                $text = '';
                foreach($contents as $i=>$content) {
                    $text .= $contents[$i];
                }
                return $text;
            }
            $zip->close();
        }
        return "";
    }

Please let me know if there is a way to fetch text content from Doc file.


回答1:


Well I finally got the Answer, so thought I should share it here. I simply used COM Objects:

$DocumentPath="C:/xampp/htdocs/abcd.doc";

$word = new COM("word.application") or die("Unable to instantiate application object");

$wordDocument = new COM("word.document") or die("Unable to instantiate document object");

$word->Visible = 0;

$wordDocument = $word->Documents->Open($DocumentPath);

$HTMLPath = substr_replace($DocumentPath, 'html', -3, 3);

$wordDocument->SaveAs($HTMLPath, 3);

$wordDocument = null;

$word->Quit();

$word = null;

readfile($HTMLPath);

unlink($HTMLPath);


来源:https://stackoverflow.com/questions/19922322/is-there-a-way-to-read-doc-files-in-php-similar-to-docx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!