获取word的xml后,可用以下方式将所有的公式都提取并转换成mathml格式,再根据 自己的业务场景进行转换成latex、公式图片即可,mathml可用mathjax直接渲染。文章来源地址https://uudwc.com/A/vmppa
// 解析xml
$xml_document_weizhi = stripos($xml, '<w:body>');
$xml_document = substr($xml, 0, $xml_document_weizhi);
$mml_arrs= [];
// 提取所有的公式,转化成mathml
libxml_disable_entity_loader(false);
preg_replace_callback('/(<m:oMath>)([\s\S]*?)(<\/m:oMath>)/', function ($matches) use ($xml_document,&$mml_arrs) {
$mml =$xml_document.'<w:body><m:oMathPara>' . $matches[0] . '</m:oMathPara></w:body></w:document>';
$domDocument = new DOMDocument();
$domDocument->loadXML($mml);
$numberings = $domDocument->getElementsByTagNameNS('http://schemas.openxmlformats.org/wordprocessingml/2006/main', 'body');
$numberings = $numberings->item(0);
$xsl = new DOMDocument();
$xsl->load('OMML2MML.XSL');
$processor = new XSLTProcessor();
$processor->importStyleSheet($xsl);
$omml = $processor->transformToXML($numberings);
$omml = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $omml);
$omml = str_replace('xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"', '', $omml);
$omml = str_replace("mml:", '', $omml);
$omml = str_replace("\n", '', $omml);
// 上面转换后部分公式非斜体,但是使用mathjax渲染时还是斜体,就把mi改成mo
$omml = str_replace("<mi mathvariant=\"normal\">'</mi>","<mo mathvariant=\"normal\">'</mo>",$omml);
$omml = str_replace("<mi>'</mi>","<mo>'</mo>",$omml);
// 公式中的导数符号被解析成了单引号,经过尝试后用如下格式的mathml使用mathjax渲染后可用!
$omml = str_replace("<mo>'</mo>","<msup><mi></mi><mo>'</mo></msup>",$omml);
// 将公式中的斜体的中文都改成正体,在word中明明已取消了斜体,但是解析道德还是斜体,故批量把斜体中文改成正常字体
$omml = preg_replace('/<mi>([\x{4e00}-\x{9fa5}]+)<\/mi>/isu','<mo>$1</mo>',$omml);
$mml_arrs[] = $omml;
return "";
}, $xml);
文章来源:https://uudwc.com/A/vmppa