最近项目遇到一个需求,网页上传docx文档,将其内容导入到富文本编辑器中。
-
方案一:phpword读取word内容,将内容放进编辑器;
结果:文档中带有超链接的文字统统被过滤掉了,原因不明,百度谷歌亦不得其解。遂放弃! -
方案二:使用windows下的COM组件,但是本人环境均是Linux,遂又放弃!
-
方案三:使用LibOffice读取word内容,将其转换为html代码。
实现步骤:(以centos为例)
- 安装LibOffice:
yum install libreoffice
很多都是下载安装包啥啥的,本人懒,就这么着! - 为了防止中文乱码,咱们再来装上中文语言支持:
yum -y install libreoffice-langpack-zh-Han*
- 为了能够命令行启动,再来安装一下一个支持库:
yum install libreoffice-headless
- 安装unoconv;LibOffice可以方便的打开多文档格式并按需进行转换,但要一次处理大量文件或要编写脚本进行转换时,仅用LibOffice就难以胜任了。 用unoconv就可以轻松地实现利用LibOffice可以打开的文档的转换.
wget https://raw.githubusercontent.com/dagwieers/unoconv/master/unoconv
chmod +x unoconv
ln -s /usr/libreoffice/unoconv /usr/bin/unoconv
yum install unoconv
- 接下来就是PHP操作环节(TP5为例):
- 上传文件的处理
public function index()
{
if (\request()->file("file")) {
$file = \request()->file('file');
$info = $file->move('./uploads/word2html');
if ($info) {
$path = '/uploads/word2html/' . $info->getSaveName();
$content = $this->word_import($path);
$res = [
'code' => 1,
'msg' => 'OK',
'data' => $content,
];
return \json_encode($res);
}
}
}
- 对word文档的转换处理
注意:shell_exec
是Linux的命令,所以文件的路径必须是Linux命令能够执行到的路径!!!还有一点更重要:用命令行执行php 转换可行的时候,浏览器却不执行,原因在于代码里的注释,好好看!没有sudoers的话请先安装sudo
function word_import($source)
{
$dir = dirname($source);
$filename = strstr(basename($source), '.', true) . '.html';
$html = $dir . '/html/' . $filename;
/*这里能够执行的条件:必须把www加入root权限组,并且设置为不需要root密码:设置步骤:打开/etc/sudoers文件,100行左右的地方加上:
'www ALL=(ALL) NOPASSWD: ALL'这么一句*/
shell_exec('sudo /usr/bin/unoconv -f html -o ' . '/mnt/d/www/wwwroot/www.demo.com/public' . $html . ' ' . '/mnt/d/www/wwwroot/www.demo.com/public' . $source);
$content = file_get_contents('.' . $html);
//取body内容,去除样式等其他
preg_match("/<body.*?>(.*?)<\/body>/is", $content, $match);
$body = trim($match[0]);
//设置保留标签,利用php自带的函数清除html格式。保留指定标签
$body = strip_tags($body, "<p><a><h1><h2><h3><h4><h5><h6><img><em><b><strong><br /><center><dl><dd><dt><ul><li><ol><i><span><pre><section><table><th><td><tr><thead><title><video>");
//图片保存到本地
$str = str_replace('<img src="', '<img src="' . $dir . '/html/', $body);
return $str;
}
网友评论