Search code examples
phpphpword

Nesting sections or reordering sections in PHPWord


I am new to using this PHPWord library and I am liking it so far.

If someone could help me figure this out or confirm for me if this is even possible or not I would greatly appreciate it.

It seems as though the sections need to be created in the order which you want them to appear on the page, but I'm looking for a way to re-ordering them, or better yet, even nesting them within one another.

$pSectionPointer = $oPHPWord->addSection();
$pAnotherSectionPointer = $oPHPWord->addSection();
$pFirstSectionPointer = $oPHPWord->addSection();

They appear in the document in the order in which I construct them, which is fine some of the time, but later in my code I may or may not want to change the order of the sections based on some new data in my code. So I want to move the $pFirstSectionPointer to before the $pSectionPointer.

How can I do this?

I've tried setting/changing the elementId and other properties of the sections using setters provided in the API to try and change the order, but there is no explanation for each method and none of them seem to do what I am wanting to do.


Solution

  • After poking around the PhpWord code a bit, neither of these (nesting or reordering) seem to be possible: Sections are only allowed in the main level (not inside another section) and the library doesn't offer any methods for changing the sections ordering (the resulting section order looks to be based on the $sections array where the new sections are appended - upon addSection function call - in PhpWord.php and that array cannot be modified via the API calls).

    If you really need to have some reordering possibility of the sections, you could try to modify the PhpWord.php file yourself a bit with the functions you need: I quickly tested this with simple content and with a simple function to just reverse the existing sections array. With these I got a result document with reversed section order without problems...