如何使用 PHPWord 从文档中编辑 headers/footers?

How to edit headers/footers from a document using PHPWord?

我正在使用 PHPWord 创建文档。我需要做的是编辑现有 docx/odt 文档的 header/footer 内容。将内容添加到文档中并不难。但是我花了一整天的时间在互联网上寻找解决方案。这是我只能通过它向现有 header/footer 内容添加内容的代码:

$source = "DumpFiles/".$_FILES['file']['name'];
    $fileName = $_FILES['file']['name'];
    $phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
    echo "File Loaded";

    // Get Sections from the imported document...
    $sections = $phpWord->getSections();
    $section = $sections[0];

    // Adding Header and Footer Content
    if(isset($_POST['headerContent']) && $_POST['headerContent']!=null)
    {
        $headert = $section->createHeader();
        $table = $headert->addTable();
        $table->addRow();
        $table->addCell(4500)->addText($_POST['headerContent']);
    }
    if(isset($_POST['footerContent']) && $_POST['footerContent'])
    {
        $footervar = $section->createFooter();
        $table = $footervar->addTable();
        $table->addRow();
        $table->addCell(4500)->addText($_POST['footerContent']);
    }

我知道直接使用 global 变量是一种不好的做法。 :-p

一旦现有代码正常运行,我将纠正代码中的这些差异。

非常感谢带有示例的解决方案。

您可以通过以下方式访问现有的 header 内容(已简化以使其更短,即缺少所有存在和类型检查):

$headers = $section->getHeaders();
$header1 = $headers[1]; // note that the first index is 1 here (not 0)

$elements = $header1->getElements();
$element1 = $elements[0]; // and first index is 0 here normally

// for example manipulating simple text information ($element1 is instance of Text object)
$element1->setText("This is my text addition - old part: " . $element1->getText());

访问页脚数据非常相似:

$footers = $section->getFooters();

另一种方式是这样的:

$PHPWord = new PHPWord();
$section = $PHPWord->createSection();
$header = $section->createHeader();
$header->addImage('images/header.png');
$footer = $section->createFooter();
$footer->addImage('images/footer.png');