
About PHPWord
Note: Though I took help from http://jeroen.is/phpword-templates-with-repeating-rows/ to write this post, I like open office xml (oox) technique given in http://officeopenxml.com/. I saw that oox is more powerful and reliable for coding for PHPWord. You should learn oox instead of this tutorial.
PHPWord template add table
When we load any template, we can set the value of any variable with setValue() function. Unfortunately we can’t add table cell/row dynamically to any template. But you can do it using my techniques ‘PHPWord template add table’. How it works:- Create a template Word document, containing the tables you would like to use.For each table, add one row to use as a template with the tags you would like to replace. Your template would be something like this:
FIRST NAME | LAST NAME |
${first_name} | ${last_name} |
- Call the cloneRow($variable, $numberOfRows) function before setValue() to duplicate the template row. Provide any variable on that row as $variable and the required number of rows as $numberOfRows. For example, calling cloneRow('first_name', 3) would transform the working copy of your template into something like this:
FIRST NAME | LAST NAME |
${first_name#1} | ${last_name#1} |
${first_name#2} | ${last_name#2} |
${first_name#3} | ${last_name#3} |
- Now call setValue($variable, $value) adding #rowNumber to the original tags.To finish the example:
$doc->setValue(‘first_name#1′, ‘Rejaul’);$doc->setValue(‘last_name#1′, ‘Karim’);$doc->setValue(‘first_name#2′, ‘Gumoti’);$doc->setValue(‘last_name#2′, ‘dotcom’);$doc->setValue(‘first_name#3′, ‘Bangla’);$doc->setValue(‘last_name#3′, ‘desh’);
FIRST NAME | LAST NAME |
Rejaul | Karim |
Gumoti | dotcom |
Bangla | desh |
/*** Clone a table row** @param mixed $search* @param mixed $numberOfClones*/public function cloneRow($search, $numberOfClones) {if(substr($search, 0, 2) !== ‘${‘ && substr($search, -1) !== ‘}’) {$search = ‘${‘.$search.’}';}$tagPos = strpos($this->_documentXML, $search);$rowStartPos = strrpos($this->_documentXML, “_documentXML) – $tagPos) * -1));$rowEndPos = strpos($this->_documentXML, “”, $tagPos) + 7;$result = substr($this->_documentXML, 0, $rowStartPos);$xmlRow = substr($this->_documentXML, $rowStartPos, ($rowEndPos – $rowStartPos));for ($i = 1; $i <= $numberOfClones; $i++) {$result .= preg_replace(‘/${(.*?)}/’,'${\1#’.$i.’}', $xmlRow);}$result .= substr($this->_documentXML, $rowEndPos);$this->_documentXML = $result;}
0 komentar:
Posting Komentar