简体   繁体   中英

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

I am trying to upload one docx file containing some contents as well as images. I want to store the file's content and images should be stored into Database. I am using php and mysql. I have trying like:

<?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.';
}

You can already get the $content using your code.

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

Now all you need to do is to parse the content as an XML file:

You need to get all 'w:p' elements (which are paragraphs), get their text (everything that is inside a 'w:t' tag), and join all those blocks together with '\\n' to create the paragraphs.

For the images, you can get them in the folder /word/media/*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM