PHP code example of mkgrow / content-control

1. Go to this page and download the library: Download mkgrow/content-control library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mkgrow / content-control example snippets



MkGrow\ContentControl\ContentControl;

// Create a new document
$cc = new ContentControl();
$section = $cc->addSection();

// Add text element
$text = $section->addText('This field is protected');

// Wrap with Content Control
$cc->addContentControl($text, [
    'alias' => 'Protected Field',
    'tag' => 'field_1',
    'type' => ContentControl::TYPE_RICH_TEXT,
    'lockType' => ContentControl::LOCK_SDT_LOCKED
]);

// Save the document
$cc->save('protected_document.docx');


use MkGrow\ContentControl\ContentProcessor;

// Open existing template
$processor = new ContentProcessor('template.docx');

// Replace SDT content by tag
$processor->replaceContent('field_1', 'Updated value');

// Update text while preserving formatting
$processor->setValue('field_2', 'New text');

// Save changes
$processor->save('output.docx');


use MkGrow\ContentControl\ContentControl;
use MkGrow\ContentControl\Bridge\TableBuilder;

// Create document and table via PHPWord API
$cc = new ContentControl();
$section = $cc->addSection();
$table = $section->addTable(['borderSize' => 6, 'borderColor' => '1F4788']);

// Build table using native PHPWord API
$row = $table->addRow();
$row->addCell(3000)->addText('Name', ['bold' => true]);
$row->addCell(3000)->addText('Value', ['bold' => true]);

$row2 = $table->addRow();
$row2->addCell(3000)->addText('Item 1');
$priceCell = $row2->addCell(3000);
$priceText = $priceCell->addText('$100');

// Wrap elements with Content Controls via TableBuilder
$builder = new TableBuilder($table);
$builder->addContentControl($priceText, [
    'tag' => 'price_1',
    'alias' => 'Price',
    'inlineLevel' => true,   // Required for cell-level elements
    'runLevel' => true,      // Wraps <w:r> instead of <w:p>
    'lockType' => ContentControl::LOCK_SDT_LOCKED,
]);

$cc->save('table_document.docx');

$cc = new ContentControl();
$section = $cc->addSection();
$text = $section->addText('Protected content');

$cc->addContentControl($text, [
    'id' => '12345678',  // Optional, auto-generated if omitted
    'alias' => 'Display Name',
    'tag' => 'metadata-id',
    'type' => ContentControl::TYPE_RICH_TEXT,
    'lockType' => ContentControl::LOCK_SDT_LOCKED,
    'inlineLevel' => false  // true for cell-level elements
]);

$cc->save('output.docx');

// 1. Open template
$processor = new ContentProcessor('template.docx');

// 2. Modify SDTs
$processor->replaceContent('field_1', 'New value');
$processor->setValue('field_2', 'Text with preserved formatting');

// 3. Replace GROUP SDT with complex structure
$complexStructure = new ContentControl();
$section = $complexStructure->addSection();
$table = $section->addTable();
// ... build complex content
$processor->replaceGroupContent('group_placeholder', $complexStructure);

// 4. Save
$processor->save('output.docx');

// Create table via PHPWord directly
$cc = new ContentControl();
$section = $cc->addSection();
$table = $section->addTable(['borderSize' => 6, 'borderColor' => '1F4788']);

$row = $table->addRow();
$cell = $row->addCell(3000);
$text = $cell->addText('Protected Value');

// Pass Table to TableBuilder, register SDTs
$builder = new TableBuilder($table);
$builder->addContentControl($text, [
    'tag' => 'value-1',
    'runLevel' => true,       // Wrap <w:r> instead of <w:p>
    'inlineLevel' => true,    // Element is inside a cell
]);

$cc->save('output.docx');

// Build table in new ContentControl
$cc = new ContentControl();
$builder = new TableBuilder($cc);
// ... build table via fluent or direct API

// Inject into template
$processor = new ContentProcessor('template.docx');
$builder->injectInto($processor, 'placeholder-tag');
$processor->save('output.docx');

$config = [
    'id' => '12345678',           // 8-digit ID (auto-generated if omitted)
    'alias' => 'Display Name',     // Name shown in Word UI
    'tag' => 'metadata_id',        // Programmatic identifier
    'type' => ContentControl::TYPE_RICH_TEXT,  // SDT type
    'lockType' => ContentControl::LOCK_SDT_LOCKED,  // Protection level
    'inlineLevel' => false,        // true for cell-level elements (REQUIRED)
    'runLevel' => false            // true to wrap <w:r> instead of <w:p> (v0.6.0+)
];

$tableStyles = [
    'borderSize' => 6,          // Border width in eighths of a point
    'borderColor' => '1F4788',  // Hex color without #
    'cellMargin' => 80,         // Default cell margin in twips
    'alignment' => 'center',    // left, center, right
    'width' => 100,             // Table width
    'unit' => 'pct',            // pct (percentage) or dxa (twips)
    'layout' => 'autofit'       // fixed or autofit
];

$builder->setStyles($tableStyles);

use MkGrow\ContentControl\Exception\ContentControlException;
use MkGrow\ContentControl\Exception\DocumentNotFoundException;
use MkGrow\ContentControl\Exception\ZipArchiveException;
use MkGrow\ContentControl\Exception\TemporaryFileException;

use MkGrow\ContentControl\ContentControl;
use MkGrow\ContentControl\Exception\ContentControlException;

try {
    $cc = new ContentControl();
    $section = $cc->addSection();
    $text = $section->addText('Content');
    
    $cc->addContentControl($text, [
        'id' => '12345678',
        'tag' => 'field_1'
    ]);
    
    $cc->save('output.docx');
    
} catch (ContentControlException $e) {
    // Library-specific errors
    error_log("ContentControl error: " . $e->getMessage());
    
} catch (\InvalidArgumentException $e) {
    // Invalid parameters
    error_log("Invalid argument: " . $e->getMessage());
    
} catch (\RuntimeException $e) {
    // General runtime errors
    error_log("Runtime error: " . $e->getMessage());
}

   // Throws InvalidArgumentException
   $cc->addContentControl($text, ['tag' => 'field_1']);
   $cc->addContentControl($text, ['tag' => 'field_2']);  // Same element!
   

   $cc->addContentControl($text1, ['id' => '12345678']);
   $cc->addContentControl($text2, ['id' => '12345678']);  // ID collision!
   

   // Throws InvalidArgumentException
   $cc->addContentControl($text, ['id' => '123']);  // Must be 8 digits
   

   // SDT wrapping may fail or wrap incorrect element
   $cellText = $cell->addText('Value');
   $cc->addContentControl($cellText, ['tag' => 'cell_1']);  // Missing inlineLevel!
   
   // CORRECT:
   $cc->addContentControl($cellText, [
       'tag' => 'cell_1',
       'inlineLevel' => true  // REQUIRED
   ]);
   

   $builder->addRow();  // Table created
   $builder->setStyles([...]);  // Throws ContentControlException!
   
   // CORRECT:
   $builder->setStyles([...])->addRow();
   

   $builder = new TableBuilder($cc);
   $row = $builder->addRow();
   $row->addCell();
   $builder->injectInto($cc, 'tag');  // Type error! Expects ContentProcessor
   
   // CORRECT for template injection:
   $processor = new ContentProcessor('template.docx');
   $builder->injectInto($processor, 'tag');
   

use MkGrow\ContentControl\ElementIdentifier;

// Get cache stats
$stats = ElementIdentifier::getCacheStats();
echo "Cached markers: " . $stats['markers'] . "\n";
echo "Cached hashes: " . $stats['hashes'] . "\n";

// Clear cache if needed (testing only)
ElementIdentifier::clearCache();

expect($xml)->toBeValidXml();  // Validates XML well-formedness

expect($xml)->toHaveXmlElement('w:sdt');  // Checks element via XPath

expect($xml)->toHaveXmlAttribute('w:id', '12345678');  // Verifies attribute
bash
composer analyse
bash
composer analyse