Search code examples
phpphpword

Replacing placeholders in a link in Word document using PHPWord


I have been using PHPWord to replace text in word documents from within PHP using setValue and it works great. But PHPWord doesn't replace placeholders inside a URL of a linked text. Is there a way this can be done?

I have done a lot of search to find a solution to this problem but not getting any. If anyone knows how to do it with some other package (instead of PHPWord), I am ready to change to that package as well.

Added after getting two votes for closing this topic: Please do not vote to close this if you do not know what I am talking about. There is a specific question asked here about PHPWord, which users of PHPWord will understand clearly. Nor am I asking others to find out a new package for me. There may be users how got stuck with this limitation of PHPWord and found an alternate package that overcomes this limitation which I was not able to find after googling.


Solution

  • I ended up creating a custom solution to open the .zip file in PHP using Ziparchive class and doing search replace in:

    document.xml - Content of the documents are in this file footerX.xml, headerX.xml - X is a number from 1 to N. So if you have only one header in your document with 5 or 10 or 100 pages, your header content will be in header1.xml; if you have 2 headers in your document, you will have those 2 header contents in header1.xml and header2.xml and so on.

    rels/document.xml.rels - Links in the document are either stored inline in document.xml or are stored in this document.xml.rels file.

    rels/footerX.xml.rels, rels/headerX.xml.rels - Links in headers and footers are stored either inline of in these files.

    Example to change links:

    $zip = new \ZipArchive();
    if ($zip->open($docFile) === TRUE) {
        $content = $zip->getFromName('word/_rels/document.xml.rels');
        $content = str_replace('google.com', 'stackoverflow.com', $content);
        $zip->addFromString('word/_rels/document.xml.rels', $content);
        $zip->close();
    }