Find linebreaks in a docx file using PHP

旧巷老猫 提交于 2019-12-10 16:00:40

问题


My PHP script successfully reads all text from a .docx file, but I cannot figure out where the line breaks should be so it makes the text bunched up and hard to read (one huge paragraph). I have manually gone over all of the XML files to try and figure it out but I cannot figure it out.

Here are the functions I use to retrieve the file data and return the plain text.

    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 "";
} 

回答1:


It is actually quite a simple answer. All you need to do is add this line in readZippedXML():

$xmldata = str_replace("</w:p>", "\r\n", $xmldata);

This is because </w:p> is what word uses to mark the end of a paragraph. E.g.

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



回答2:


Actually, why don't you use OpenXML? I think it works with PHP too. And then you don't have to go down to the nitty gritty file xml details.

Here is a link:
http://openxmldeveloper.org/articles/4606.aspx



来源:https://stackoverflow.com/questions/5607594/find-linebreaks-in-a-docx-file-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!