php method to convert html to word: 1. Generate word through mnt media, the code is [composer require cshaptx4869/html2word]; 2. Write the html file directly into word, and convert the image to base64 format.
How to convert html to word using php:
1. Generate word
through the medium of mntcomposer require cshaptx4869/html2word
<?php /** * @desc 方法一、生成word文档 * @param $content * @param string $fileName */ function createWord($content = '', $fileName = '') { if (empty($content)) { return; } $content='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"> <meta charset="UTF-8" />'.$content.'</html>'; if (empty($fileName)) { $fileName = date('YmdHis').'.doc'; } file_put_contents($fileName, $content); }
2. Write the html file directly into word
Note: If there are pictures, convert them to base64 format
<?php/** * @desc 方法二、生成word文档并下载 * @param $content * @param string $fileName */ function downloadWord($content, $fileName=''){ if(empty($content)){ return; } if (empty($fileName)) { $fileName = date('YmdHis').'.doc'; } // header("location:xxx.doc"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename={$fileName}"); $html = '<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40">'; $html .= '<head><meta http-equiv="Content-Type" content="text/html;charset="UTF-8" /></head>'; echo $html . '<body>'.$content .'</body></html>'; } createWord(file_get_contents('html2word.html')); downloadWord(file_get_contents('html2word.html'));
Related learning recommendations:Getting started with PHP programming To master
The above is the detailed content of How to convert html to word in php?. For more information, please follow other related articles on the PHP Chinese website!