有很好的 PHP 库,但它不是免费的:
http://www.phpdocx.com/documentation/introduction/html-to-word-PHP
如果你只是想在你的word模板中替换一些文本(我建议你使用docx格式)你可以解压docx文件,你会找到XML文件这个内容。
所以,你可以使用 str_replace('{{youVariableInWordTemplate}}', $value, $wordXML);
另一种方式:使用 PhpWord
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$html = '<p><strong>You html here</strong></p>';
Html::addHtml($section, $html);
$objWriter = IOFactory::createWriter($phpWord, 'Word2007');
$cacheDir = '/temp_directory_of_your_project/';
$objWriter->save($cacheDir. 'helloWorld.docx');
但是这个库在表格生成方面存在问题。有未解决的问题:Using table tag in HTML Reader produces no output 使用自定义类的解决方案(见帖子中的附件)
您还可以找到改进的实现:HTML Reader from PHPWord does't work with tables?
这个库支持的 HTML 标签不多(下面有支持标签的数组):
$nodes = array(
// $method $node $element $styles $data $argument1 $argument2
'p' => array('Paragraph', $node, $element, $styles, null, null, null),
'h1' => array('Heading', null, $element, $styles, null, 'Heading1', null),
'h2' => array('Heading', null, $element, $styles, null, 'Heading2', null),
'h3' => array('Heading', null, $element, $styles, null, 'Heading3', null),
'h4' => array('Heading', null, $element, $styles, null, 'Heading4', null),
'h5' => array('Heading', null, $element, $styles, null, 'Heading5', null),
'h6' => array('Heading', null, $element, $styles, null, 'Heading6', null),
'#text' => array('Text', $node, $element, $styles, null, null, null),
'span' => array('Span', $node, null, $styles, null, null, null), //to catch inline span style changes
'strong' => array('Property', null, null, $styles, null, 'bold', true),
'em' => array('Property', null, null, $styles, null, 'italic', true),
'sup' => array('Property', null, null, $styles, null, 'superScript', true),
'sub' => array('Property', null, null, $styles, null, 'subScript', true),
'table' => array('Table', $node, $element, $styles, null, 'addTable', true),
'tbody' => array('Table', $node, $element, $styles, null, 'skipTbody', true), //added to catch tbody in html.
'tr' => array('Table', $node, $element, $styles, null, 'addRow', true),
'td' => array('Table', $node, $element, $styles, null, 'addCell', true),
'ul' => array('List', null, null, $styles, $data, 3, null),
'ol' => array('List', null, null, $styles, $data, 7, null),
'li' => array('ListItem', $node, $element, $styles, $data, null, null),
);