How can PHP be used to extract and display text from Word documents while preserving formatting?

To extract and display text from Word documents while preserving formatting in PHP, you can use the PHPWord library. This library allows you to read Word documents and extract text with formatting intact. You can then display this text on your website or application.

// Include PHPWord library
require_once 'path/to/PHPWord/Autoloader.php';

// Load the Word document
$phpWord = \PhpOffice\PhpWord\IOFactory::load('path/to/your/document.docx');

// Get the text with formatting
$text = '';
foreach ($phpWord->getSections() as $section) {
    foreach ($section->getElements() as $element) {
        if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($element->getElements() as $textElement) {
                $text .= $textElement->getText() . ' ';
            }
        }
    }
}

// Display the text with formatting
echo $text;