phpword是一種功能強大的開源API,用PHP編寫,用於創建和讀取文件形式,包括docdocxodt,[4][rtf][rtf][rtf] 5],HTMLPDF。使用API​​,您可以創建文檔,設置文檔屬性,插入圖像,插入圖表以及更多。讓我們開始使用phpword創建一個簡單的docx文件。

先決條件

要使用phpword創建Word文檔,您需要在操作系統中安裝以下資源:

  • PHP版本5.3.3+

  • 作曲家

  • [XML解析器擴展10] ( This extension is enabled by default )

  • Zend Escaper Componen T(您可以使用以下命令安裝它)

composer require zendframework/zend-escaper
  • [Zend STDLIB Component12] (You can install it using the following command)
composer require zendframework/zend-stdlib

如何安裝phpword

之後,您準備就緒前提條件,可以使用簡單的作曲家命令安裝PHPWOWE:

composer require phpoffice/phpword

使用PHP創建Word文檔

創建Word文檔很簡單。您需要使用 phpword() 方法創建一個新文檔,使用 addSection() 方法創建一個新部分,然後使用 addtext() 方法在其中添加文本。以下是創建簡單Word文檔的代碼片段。

<?php
require_once 'vendor\phpoffice\phpword\bootstrap.php';

// Create the new document..
$phpWord = new \PhpOffice\PhpWord\PhpWord();

// Add an empty Section to the document
$section = $phpWord->addSection();
// Add Text element to the Section
$section->addText(
    'File Format Developer Guide - '
    . 'Learn about computer files that you come across in '
    . 'your daily work at: www.fileformat.com'
);
// Save document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('D:\HelloWorld.docx');

以下是輸出文檔: *