在php中读取DOC文件

no_*_*dom 14 php

我正在尝试.doc .docx在php中读取文件.一切都很好.但是在最后一行我变得很可怕.请帮我.这是由某人开发的代码.

    function parseWord($userDoc) 
{
    $fileHandle = fopen($userDoc, "r");
    $line = @fread($fileHandle, filesize($userDoc));   
    $lines = explode(chr(0x0D),$line);
    $outtext = "";
    foreach($lines as $thisline)
      {
        $pos = strpos($thisline, chr(0x00));
        if (($pos !== FALSE)||(strlen($thisline)==0))
          {
          } else {
            $outtext .= $thisline." ";
          }
      }
     $outtext = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$outtext);
    return $outtext;
} 

$userDoc = "k.doc";
Run Code Online (Sandbox Code Playgroud)

这是截图. 在此输入图像描述

小智 15

您可以在PHP中读取.docx文件,但无法读取.doc文件.这是读取.docx文件的代码:

function read_file_docx($filename){

    $striped_content = '';
    $content = '';

    if(!$filename || !file_exists($filename)) return false;

    $zip = zip_open($filename);

    if (!$zip || is_numeric($zip)) return false;

    while ($zip_entry = zip_read($zip)) {

        if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

        if (zip_entry_name($zip_entry) != "word/document.xml") continue;

        $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

        zip_entry_close($zip_entry);
    }// end while

    zip_close($zip);

    //echo $content;
    //echo "<hr>";
    //file_put_contents('1.xml', $content);

    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
    $content = str_replace('</w:r></w:p>', "\r\n", $content);
    $striped_content = strip_tags($content);

    return $striped_content;
}
$filename = "filepath";// or /var/www/html/file.docx

$content = read_file_docx($filename);
if($content !== false) {

    echo nl2br($content);
}
else {
    echo 'Couldn\'t the file. Please check that file.';
}
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到SO,在这里,解释为什么要使用您的解决方案而不仅仅是如何解释这是一个很好的做法.这将使您的答案更有价值,并帮助读者更好地了解您的工作方式.我还建议您查看我们的常见问题解答:http://stackoverflow.com/faq. (4认同)

Ste*_*e-o 7

DOC文件不是纯文本.

尝试使用PHPWord(旧的CodePlex站点)等库.

nb:这个答案已经多次更新,因为PHPWord已经改变了主机和功能.

  • PHPWord不提供读取DOC文件的功能. (14认同)
  • 而.docx是一个包含多个文件的.zipped包 (3认同)
  • 另外,请注意PHPWord是__NOT__:它是由一组独立开发人员编写的免费开源库,不受MS支持或认可. (3认同)