Home  >  Article  >  Backend Development  >  How to Properly Parse .DOC Files in PHP and Avoid Character Interpretation Errors?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 06:21:28831browse

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>

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>

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!

Statement:
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