首頁  >  文章  >  後端開發  >  如何在 PHP 中讀取 DOCX 檔案而不包含無關字元?

如何在 PHP 中讀取 DOCX 檔案而不包含無關字元?

Susan Sarandon
Susan Sarandon原創
2024-10-25 18:06:03799瀏覽

How to Read DOCX Files in PHP without Extraneous Characters?

如何在PHP 中讀取DOC 檔案

嘗試在PHP 中讀取DOC 或DOCX 檔案時,您可能會遇到無關字符的問題文字的結尾。出現此錯誤的原因是提供的程式碼片段無法正確解析 DOC 格式。

要解決此問題,我們需要稍微修改我們的方法,因為 PHP 不支援原生 DOC 檔案解析。相反,我們將使用不同的方法來處理 DOCX 檔案。

讀取 DOCX 檔案的更新程式碼:

<code class="php">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);

    $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.';
}</code>

此更新的程式碼使用 PHP ZipArchive 類別來開啟並讀取 DOCX 檔案的內容。具體來說,它從ZIP壓縮包中提取“word/document.xml”文件,其中包含實際的文字內容。

透過使用此方法,您可以在PHP中成功讀取和解析DOCX檔案。

以上是如何在 PHP 中讀取 DOCX 檔案而不包含無關字元?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn