PHP Word : Adding & Replacing Tables

Simpler Method to Add a table : replacing a placeholder with Template Processor

<?php
//https://stackoverflow.com/questions/16794294/phpword-doesnt-replace-text
//https://phpword.readthedocs.io/en/latest/intro.html
//https://phpword.readthedocs.io/en/latest/templates-processing.html
require_once 'vendor/autoload.php';
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor;
$templatesDocsFolder = "docs/templates/";
$templatesDocName = "WPC-A4.docx";
$templatesDocPath = $templatesDocsFolder.$templatesDocName;


$generatedDocsFolder = "docs/generated/";
$generatedDocName = $templatesDocName.date('d-m-Y_his').".docx";
$generatedDocPath = $generatedDocsFolder.$generatedDocName;

//Create table
$document_with_table = new PhpWord();
$section = $document_with_table->addSection();
$table = $section->addTable();
for ($r = 1; $r <= 8; $r++) {
    $table->addRow();
    for ($c = 1; $c <= 5; $c++) {
        $table->addCell(1750)->addText("Row {$r}, Cell {$c}");
    }
}

// Create writer to convert document to xml

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($document_with_table, 'Word2007');

// Get all document xml code
$fullxml = $objWriter->getWriterPart('Document')->write();

// Get only table xml code
$tablexml = preg_replace('/^[\s\S]*(<w:tbl\b.*<\/w:tbl>).*/', '$1', $fullxml);
$matched = preg_match_all('/^[\s\S]*(<w:tbl\b.*<\/w:tbl>).*/sU',  $fullxml,$matches);
//die("<pre>".print_r($matches,true)."</pre>");

//Open template with ${table}
$template_document = new \PhpOffice\PhpWord\TemplateProcessor($templatesDocPath);

// Replace mark by xml code of table
$template_document->setValue('table', $tablexml);

//save template with table
$template_document->saveAs($generatedDocPath);
?>

Replace an Existing Table with ZipArchive Class

<?php
require_once 'vendor/autoload.php';
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor;

function read_docx($filename){

    $striped_content = '';
    $content = '';

    if(!$filename || !file_exists($filename)) return false;

    $zip = zip_open($filename);
    if (!$zip || is_numeric($zip)) return false;

    while ($zip_entry = zip_read($zip)) {

        if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

        if (zip_entry_name($zip_entry) != "word/document.xml") continue;

        $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

        zip_entry_close($zip_entry);
    }
    zip_close($zip);      
    /* $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
    $content = str_replace('</w:r></w:p>', "\r\n", $content);
    $striped_content = strip_tags($content);

    return $striped_content; */
    return $content; 
}

//Create table
$document_with_table = new PhpWord();
$section = $document_with_table->addSection();
$table = $section->addTable();
for ($r = 1; $r <= 8; $r++) {
    $table->addRow();
    for ($c = 1; $c <= 5; $c++) {
        $table->addCell(1750)->addText("Row {$r}, Cell {$c}");
    }
}
$templatesDocsFolder = "docs/templates/";
$templatesDocName = "WPC-A4.docx";
$templatesDocPath = $templatesDocsFolder.$templatesDocName;


$generatedDocsFolder = "docs/generated/";
$generatedDocName = $templatesDocName.date('d-m-Y_his').".docx";
$generatedDocPath = $generatedDocsFolder.$generatedDocName;

// Create writer to convert document to xml

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($document_with_table, 'Word2007');

// Get all document xml code
$fullxml = $objWriter->getWriterPart('Document')->write();
$tablexml = preg_replace('/^[\s\S]*(<w:tbl\b.*<\/w:tbl>).*/', '$1', $fullxml);

$templateDoc = $templatesDocPath;
$fullxml = read_docx($templateDoc);


//echo $fullxml;
//$matched = preg_match_all('/^[\s\S]*(<w:tbl\b.*<\/w:tbl>).*/isU',  $fullxml,$matches);
$matched = preg_match_all('/(<w:tbl\b.*<\/w:tbl>)/isU',  $fullxml,$matches);
$tableXML2Replace = $matches[1][5];
//die("<pre>".print_r($matches,true)."</pre>");

// Creating the new document...
$zip = new \PhpOffice\PhpWord\Shared\ZipArchive();

//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';

$file = $templatesDocPath;
$temp_file = $generatedDocPath;
copy($file,$temp_file);


if ($zip->open($temp_file) === TRUE) {
    //Read contents into memory
    $oldContents = $zip->getFromName($fileToModify);

    echo $oldContents;

    //Modify contents:
    $newContents = str_replace($tableXML2Replace, $tablexml, $oldContents);
    

    //Delete the old...
    $zip->deleteName($fileToModify);
    //Write the new...
    $zip->addFromString($fileToModify, $newContents);
    //And write back to the filesystem.
    $return =$zip->close();
    If ($return==TRUE){
        echo "Success!";
    }
} else {
    echo 'failed';
}
?>