How to extract images from DOCX files using PHP

In this post I will show you how to extract and display images from Microsoft Word Document files (docx extension) using PHP. This can be used for creating a document repository and indexing images for it. We won't use any third party software or module for this. This code will work in PHP 5.2+ and the only requirement is php_zip.dll for Windows or --enable-zip parameter for Linux. Basically we need a ZIP library for PHP. The reason behind this requirement is that Word document files are actually archived files with there extension changed from .zip to .docx.

Try to open a docx file with a ZIP file utility. See below the screenshot of a docx file named attractive_prices.docx extracted with WINRAR.

A docx file extracted with ZIP file utility

As you can see there are various folders and XML files inside this archive. We can even extract the text from the document file! Indeed my next post will be on this. All the media files are stored by Word in directory - word/media.

So if we want to extract and display images from a doc file, all we need to do is open the word/media directory present in the archive and then display all the images present inside it.

Create a new PHP file and name it as extract.php and add the following code in it. 

<?php

/*Name of the document file*/
$document = 'attractive_prices.docx';

/*Function to extract images*/ 
function readZippedImages($filename) {

/*Create a new ZIP archive object*/
    $zip = new ZipArchive;

    /*Open the received archive file*/
    if (true === $zip->open($filename)) {
for ($i=0; $i<$zip->numFiles;$i++) {

/*Loop via all the files to check for image files*/
$zip_element = $zip->statIndex($i);

/*Check for images*/
if(preg_match("([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)",$zip_element['name'])) {

/*Display images if present by using display.php*/
echo "<image src='display.php?filename=".$filename."&index=".$i."' /><hr />";
}
}
}
}
readZippedImages($document);
?>

Now create another PHP file and name it as display.php and add the following code to it. 

<?php

/*Tell the browser that we want to display an image*/
header('Content-Type: image/jpeg');

/*Create a new ZIP archive object*/
    $zip = new ZipArchive;

    /*Open the received archive file*/
    if (true === $zip->open($_GET['filename'])) {

/*Get the content of the specified index of ZIP archive*/
echo $zip->getFromIndex($_GET['index']);
}

$zip->close();
?>

Comments have been included in both the scripts for easy understanding. Check out the working demo.

Tags: