label305 / docx-extractor

PHP库,用于提取和替换.docx文件中的字符串数据。

0.2.3 2024-04-30 11:59 UTC

README

PHP库,用于提取和替换.docx文件中的字符串数据。Docx文件是包含XML文档和资产的zip存档。它们的格式由OOXML描述。此库仅操作word/document.xml文件。

Composer安装

"require": {
    "label305/docx-extractor": "0.2.*"
}

要求

  • PHP 8.0
  • PHP ext-dom
  • PHP ext-zip
  • PHP ext-libxml

基本用法

导入基本类。

use Label305\DocxExtractor\Basic\BasicExtractor;
use Label305\DocxExtractor\Basic\BasicInjector;

首先,我们需要从一个现有的docx文件中提取所有段落。这可以通过使用BasicExtractorDecoratedTextExtractor来完成。调用extractStringsAndCreateMappingFile将创建一个新文件,其名称通过第二个参数传入。这个新文件包含引用,这样库就知道在哪里将修改后的文本插入回去了。

$extractor = new BasicExtractor();
$mapping = $extractor->extractStringsAndCreateMappingFile(
    'simple.docx',
    'simple-extracted.docx'
  );

现在你已经提取了段落,你可以检查结果$mapping数组的内容。如果你想更改内容,你可以简单地修改它。数组键映射到simple-extracted.docx中的一个符号。

echo $mapping[0]; // The quick brown fox jumps over the lazy dog

现在在你更改了内容之后,你可以将其保存回一个新的文件。在这个例子中,该文件是simple-injected.docx

$mapping[0] = "Several fabulous dixieland jazz groups played with quick tempo.";

$injector = new BasicInjector();
$injector->injectMappingAndCreateNewFile(
    $mapping,
    'simple-extracted.docx',
    'simple-injected.docx'
  );

高级用法

此库还配备了DecoratedTextExtractorDecoratedTextInjector,你可以使用它们来操作基本的段落样式,如粗体、斜体和下划线。你也可以使用Paragraph对象来区分文本的逻辑分组。

$extractor = new DecoratedTextExtractor();
$mapping = $extractor->extractStringsAndCreateMappingFile(
    'simple.docx',
    'simple-extracted.docx'
  );
  
$firstParagraph = $mapping[0]; // Paragraph object
$firstSentence = $firstParagraph[0]; // Sentence object

$firstSentence->italic = true;
$firstSentence->bold = false;
$firstSentence->underline = true;
$firstSentence->br = 2; // Two line breaks before this sentence

echo $firstSentence->text; // The quick brown fox jumps over the lazy dog
$firstSentence->text = "Several fabulous dixieland jazz groups played with quick tempo.";

$injector = new DecoratedTextInjector();
$injector->injectMappingAndCreateNewFile(
    $mapping,
    'simple-extracted.docx',
    'simple-injected.docx'
  );

许可证

版权所有2014 Label305 B.V.

根据Apache许可证第2版(“许可证”)授权;除非遵守许可证的条款,否则不得使用此文件。您可以在以下地址获得许可证副本:

https://apache.ac.cn/licenses/LICENSE-2.0

除非适用法律要求或书面同意,否则在许可证下分发的软件按“原样”提供,不提供任何明示或暗示的保证或条件。有关许可证的具体语言,请参阅许可证。