How to Properly Parse .DOC Files in PHP and Avoid Character Interpretation Errors?

Mary-Kate Olsen
Release: 2024-10-30 06:21:28
Original
831 people have browsed it

How to Properly Parse .DOC Files in PHP and Avoid Character Interpretation Errors?

Reading .DOC Files in PHP

Reading .DOC files in PHP can be challenging due to their binary format. However, you can parse them using the code provided by someone, but it may result in incorrect character interpretation.

To resolve this issue, you need to make the following modification:

<code class="php">$line = @fread($fileHandle, filesize($userDoc));
$lines = explode(chr(0x0A),$line);</code>
Copy after login

This change replaces the character chr(0x0D) with chr(0x0A). Windows stores newlines as rn (carriage return plus line feed), while UNIX systems use n (line feed only). By using chr(0x0D), you're treating the DOS/Windows newline character, but the file is stored in Unix format.

Additionally, consider the following code to read .docx files in PHP:

<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;
}</code>
Copy after login

This code:

  • Opens the .docx file as a ZIP archive.
  • Extracts the "word/document.xml" file.
  • Parses the XML content.
  • Removes unnecessary tags and characters.
  • Returns the parsed text content.

The above is the detailed content of How to Properly Parse .DOC Files in PHP and Avoid Character Interpretation Errors?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!