上传docx文件并使用php将内容和图像存储到数据库中


Upload docx file and store the content and images into DB using php

我正在尝试上传一个包含一些内容和图像的docx文件。我想存储文件的内容,图像应该存储到数据库中。我正在使用php和mysql。 我尝试过:

<?php
/*Name of the document file*/
$document = 'file.docx';
function get_string_between($string, $start, $end) {
        $string = " " . $string;
        $ini = strpos($string, $start);
        if ($ini == 0)
            return "";
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        return substr($string, $ini, $len);
    }
function read_file_docx($filename){
    $striped_content = '';
    $content = '';
    if(!$filename || !file_exists($filename)) return false;
    $zip = zip_open($filename);
    if (!$zip || is_numeric($zip)) return false;
    while ($zip_entry = zip_read($zip)) {
        if (zip_entry_open($zip, $zip_entry) == FALSE) continue;
        if (zip_entry_name($zip_entry) != "word/document.xml") continue;
        $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
        zip_entry_close($zip_entry);
    }// end while
    zip_close($zip);
    echo $im = get_string_between($content,"descr=","/>");
    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
//    $content = str_replace('</w:r></w:p>', "'r'n", $content);
    //$content = str_replace('</w:r></w:p>', "-viavitae-", $content);
  //  $content = str_replace('-viavitae-', $im, $content);
//    $striped_content = strip_tags($content);
    $striped_content = ($content);
//    echo get_string_between($striped_content,"descr=","/>");
    return $striped_content;
}
$content = read_file_docx($document);
if($content !== false) {
    echo nl2br($content);
}
else {
    echo 'Couldn''t the file. Please check that file.';
}

您已经可以使用代码获取$content。

$content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

现在,您需要做的就是将内容解析为 XML 文件:

您需要获取所有"w:

p"元素(即段落),获取其文本("w:t"标签内的所有内容),并将所有这些块与"'"连接在一起以创建段落。

对于图像,您可以在文件夹中获取它们/word/media/*