Search code examples
phpphpword

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


I am using PHPWord to create documents. What I need to do is edit the header/footer content of an existing docx/odt document. It was not very hard to add the content to a document. But I've spent the whole day on the internet to find a solution. Here is the code through which I am only being able to add content to existing header/footer content:

$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']);
    }

I understand that the usage of global variables directly is a bad practice. :-p

I would rectify these discrepancies in my code once I get the existing code working.

A solution with an example would be greatly appreciated.


Solution

  • You can access the existing header contents in the following way (simplified to make it shorter, i.e. missing all existence and type checks):

    $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());
    

    Access to the footer data is very similar:

    $footers = $section->getFooters();