使用PHP在docx文件中查找换行符



我的PHP脚本成功地读取了.docx文件中的所有文本,但我不知道换行符应该在哪里,所以它使文本聚集在一起,难以阅读(一个大段落)。我已经手动遍历了所有的XML文件,试图弄清楚它,但我无法弄清楚。

下面是我用来检索文件数据并返回纯文本的函数。
    public function read($FilePath)
{
    // Save name of the file
    parent::SetDocName($FilePath);
    $Data = $this->docx2text($FilePath);
    $Data = str_replace("<", "&lt;", $Data);
    $Data = str_replace(">", "&gt;", $Data);
    $Breaks = array("rn", "n", "r");
    $Data = str_replace($Breaks, '<br />', $Data);
    $this->Content = $Data;
}
function docx2text($filename) {
    return $this->readZippedXML($filename, "word/document.xml");
}
function readZippedXML($archiveFile, $dataFile)
{
    // Create new ZIP archive
    $zip = new ZipArchive;
    // Open received archive file
    if (true === $zip->open($archiveFile))
    {
        // If done, search for the data file in the archive
        if (($index = $zip->locateName($dataFile)) !== false)
        {
            // If found, read it to the string
            $data = $zip->getFromIndex($index);
            // Close archive file
            $zip->close();
            // Load XML from a string
            // Skip errors and warnings
            $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            $xmldata = $xml->saveXML();
            //$xmldata = str_replace("</w:t>", "rn", $xmldata);
            // Return data without XML formatting tags
            return strip_tags($xmldata);
        }
        $zip->close();
    }
    // In case of failure return empty string
    return "";
} 

这个答案其实很简单。您所需要做的就是在readZippedXML():

中添加这一行。
$xmldata = str_replace("</w:p>", "rn", $xmldata);

这是因为是word用来标记段落结束的符号。例如

<w:p>This is a paragraph.</w:p>
<w:p>And a second one.</w:p>

实际上,为什么不使用OpenXML呢?我认为它也适用于PHP。这样你就不用去查xml文件的细节了

这是一个链接:
http://openxmldeveloper.org/articles/4606.aspx

最新更新