Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reading/Writing a MS Word file in PHP
Microsoft strongly advises against using COM objects for Office document automation, stating: "Microsoft does not currently recommend or support the Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment."
Fortunately, .docx files can be created and manipulated without COM objects since they have XML foundations. Libraries like PHPWord and PhpSpreadsheet provide excellent solutions for working with Word documents in PHP.
Installation
Install PHPWord using Composer:
composer require phpoffice/phpword
Creating a Word Document
Here's how to create a basic Word document using PHPWord −
<?php
require_once 'vendor/autoload.php';
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
// Create new PHPWord instance
$phpWord = new PhpWord();
// Add a section to the document
$section = $phpWord->addSection();
// Add text to the section
$section->addText('Hello World! This is my first PHPWord document.');
// Add a title
$section->addText('Document Title', array('bold' => true, 'size' => 16));
// Add a paragraph
$section->addTextBreak(1);
$section->addText('This is a paragraph with some formatting.', array('italic' => true));
// Save the document
$objWriter = IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('sample.docx');
echo "Document created successfully!";
?>
Reading a Word Document
To read content from an existing Word document −
<?php
require_once 'vendor/autoload.php';
use PhpOffice\PhpWord\IOFactory;
// Load existing document
$phpWord = IOFactory::load('sample.docx');
// Get all sections
$sections = $phpWord->getSections();
echo "Document Contents:
";
foreach ($sections as $section) {
$elements = $section->getElements();
foreach ($elements as $element) {
if (method_exists($element, 'getText')) {
echo $element->getText() . "
";
}
}
}
?>
Key Advantages
- No local Word installation required − Works without Microsoft Office
- Cross-platform compatibility − Runs on Linux, Windows, and macOS
- XML-based approach − More stable and reliable than COM automation
- Rich formatting support − Handles text styling, tables, images, and more
Conclusion
Using PHPWord provides a robust, cross-platform solution for working with Word documents in PHP. This XML-based approach eliminates the need for COM objects and Microsoft Office installations, making it ideal for web applications and server environments.
