Home > Article > Backend Development > How to Properly Parse .DOC Files in PHP and Avoid Character Interpretation Errors?
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:
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!