How to convert html to word using php?
Your current approach strips all HTML tags except breaks and then manually inserts line breaks. This works for plain text, but it fails immediately when you need inline CSS styling or images. The fundamental issue is that Microsoft Word does not render HTML in the same way a browser does. If you simply write raw HTML into a .doc file using fopen and fwrite, Word will ignore almost all of it because the binary structure of the DOC format expects specific XML packaging, not a stream of tags.
To preserve inline CSS and include images, you must generate a valid OpenXML document or use a library that handles the complex binary conversion for you. Writing raw HTML to a .doc file is effectively unsupported in modern development. The standard solution involves converting your HTML into a format Word understands natively: DOCX (which is actually ZIP-compressed XML).
The Limitations of Your Current Script
The script you posted uses strip_tags() to remove everything except line breaks, then forces those breaks into the text stream. This results in a pure ASCII file with no formatting information. Even if you tried to pass an HTML string directly to that file handle without stripping tags, Word would not interpret it correctly unless you were writing a true OpenXML document.
Furthermore, embedding images in a plain text file is impossible. Images require binary data, specific MIME types, and usually a header block to be recognized by the application. The iconv function in your code also converts characters to ASCII with transliteration, which destroys UTF-8 encoding. Word expects UTF-16 or UTF-8 depending on the format version, so this step will corrupt special characters like accented letters or emojis.
Using a Dedicated PHP Library
The most reliable way to convert HTML to DOCX while preserving CSS and images is to use a dedicated library. The HTMLtoWord project (or similar packages like barryvdh/html-to-docx) abstracts the complexity of OpenXML generation. These libraries parse your HTML, apply inline styles where necessary, and package the content into a valid ZIP archive containing the word/document.xml file.
Here is how you would typically structure this in a PHP application:
use Barryvdh\Html2Docx\Html2Docx;
$html = file_get_contents('your_html_file.html');
$docx = new Html2Docx();
// Convert HTML to DOCX binary
$docx->convert($html);
// Save the output
file_put_contents('output.docx', $docx->getContent());
This approach handles the conversion logic internally. It ensures that your inline CSS styles (like color: red or background-image) are translated into Word's style system, rather than being ignored.
Handling Images in DOCX
You specifically asked about adding images. With a dedicated library, this is often handled automatically if the HTML contains <img> tags with valid paths. However, there is a critical catch: relative paths in your HTML source will not resolve correctly unless the images are physically located next to the generated .docx file or referenced via an absolute URL that the conversion tool can download and embed.
If you convert an HTML page hosted on a remote server, the library might try to fetch images from the web. This requires allow_url_fopen to be enabled in your PHP configuration and often takes longer due to network latency. For local conversions, ensure your image paths are relative to the output directory or use absolute paths pointing to files on the same filesystem where the script runs.
Why Not Just Use a Browser?
Sometimes developers consider rendering the HTML in a browser (via headless Chrome) and then saving it as a PDF or DOCX. While this works for PDF generation, Word does not support direct PDF-to-DOCX conversion perfectly because of font and layout differences. The OpenXML route remains the most robust method for maintaining fidelity to your original design.
Trade-offs to Consider
Relying on third-party libraries adds dependencies to your project. You must ensure you are using a version compatible with your PHP minor version. Additionally, complex HTML structures (like nested tables or specific CSS3 features) might still degrade in the final Word document because Word has its own rendering engine limitations. Always test the output in an actual Microsoft Word instance rather than assuming the conversion is perfect based on console logs.
For projects built on Laravel, you can integrate these libraries easily via Composer. If you are looking for managed services or specific enterprise-grade conversion tools without managing dependencies yourself, platforms like https://laravelcompany.com often discuss integration patterns for complex document workflows, though implementing the library directly is usually more cost-effective for standard needs.