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

Mas*_*erZ 4 php document ms-office

我的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("\r\n", "\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>", "\r\n", $xmldata);
            // Return data without XML formatting tags
            return strip_tags($xmldata);
        }

        $zip->close();
    }

    // In case of failure return empty string
    return "";
} 
Run Code Online (Sandbox Code Playgroud)

Jos*_*shB 9

这实际上是一个非常简单的答案.您需要做的就是添加以下行readZippedXML():

$xmldata = str_replace("</w:p>", "\r\n", $xmldata);
Run Code Online (Sandbox Code Playgroud)

这是因为</ w:p>是用于标记段落结尾的单词.例如

<w:p>This is a paragraph.</w:p>
<w:p>And a second one.</w:p>
Run Code Online (Sandbox Code Playgroud)