获取HTML中元素代码,并用phpword转换成word下载
时间: 2024-06-10 17:07:44 浏览: 5
您可以使用PHP的DOMDocument类来获取HTML元素代码,然后使用PHPWord类将其转换为Word文档,并提供下载链接。您可以参考以下代码:
```
// 获取HTML元素代码
$html = file_get_contents('http://example.com');
// 使用DOMDocument类解析HTML
$dom = new DOMDocument();
$dom->loadHTML($html);
// 获取需要转换的HTML元素
$element = $dom->getElementById('my-element-id');
$elementHtml = $dom->saveXML($element);
// 使用PHPWord类转换为Word文档
require_once 'PHPWord/vendor/autoload.php';
\PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$html = \PhpOffice\PhpWord\Shared\Html::addHtml($section, $elementHtml);
// 提供Word文档下载链接
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;filename="my-file.docx"');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('php://output');
exit;
```