xun xun - 2 years ago 204
PHP Question

How can I convert a docx document to html using php?

I want to be able to upload an MS word document and export it a page in my site.

Is there any way to accomplish this?

Answer Source
//FUNCTION :: read a docx file and return the string
function readDocx($filePath) {
    // Create new ZIP archive
    $zip = new ZipArchive;
    $dataFile = 'word/document.xml';
    // Open received archive file
    if (true === $zip->open($filePath)) {
        // 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
            // Load XML from a string
            // Skip errors and warnings
            // Return data without XML formatting tags

            $contents = explode('\n',strip_tags($xml->saveXML()));
            $text = '';
            foreach($contents as $i=>$content) {
                $text .= $contents[$i];
            return $text;
    // In case of failure return empty string
    return "";

ZipArchive and DOMDocument are both inside PHP so you don't need to install/include/require additional libraries.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download