Tutorial 3 : Repeat a part of the document (Segment) - neeftarah/odtphp GitHub Wiki
This tutorial purpose is to show how to repeat a part of your template with segments. We will see in this example how to display a list of articles in our final OpenOffice document.
The PHP code
<?php
require_once('../library/odf.php');
$odf = new odf("tutoriel3.odt");
$odf->setVars('titre', 'Quelques articles de l\'encyclopédie Wikipédia');
$message = "La force de cette encyclopédie en ligne réside...";
$odf->setVars('message', $message);
$listeArticles = array(
array('titre' => 'PHP',
'texte' => 'PHP est un langage de scripts (...)',
),
array('titre' => 'MySQL',
'texte' => 'MySQL est un système de gestion de base de données (...)',
),
array('titre' => 'Apache',
'texte' => 'Apache HTTP Server, souvent appelé Apache (...)',
),
)
$article = $odf->setSegment('articles');
foreach($listeArticles AS $element) {
$article->titreArticle($element['titre']);
$article->texteArticle($element['texte']);
$article->merge();
}
$odf->mergeSegment($article);
$odf->exportAsAttachedFile();
?>
-
We create an Odf object by specifying the path to our template. Then, we call two times the method setVars() of the created object in order to replace {titre} and {message} tags by text content.
-
For the second step, we initialize in an array a data set that we want to fully display. The array provides a list of articles consisting of a title and a text.
-
We initialize the segment "articles" with a call to the method setSegment() which takes as argument the name of the segment and returns an object of type Segment.
-
Then, We can loop on our data array. At each loop, we replace the tags {titreArticle} and {texteArticle} of segment by content of the current line of the array. For that, we directly access to the methods titreArticle() and texteArticle() of the object $article. You can also perform this replacement in a classic way by calling the method setVar() of the object $article.
-
Eventually, when we have added all our desired data, we can add the segment to the document by calling the method mergeSegment() of the object $odf which takes as parameter our segment $article.
The OpenOffice model (tutoriel3.odt)
{titre}
{message}
[!-- BEGIN articles --]
{titreArticle}
{texteArticle}
[!-- END articles --]
To run this example, copy this template within an OpenOffice document named "tutoriel3.odt". In the template, segments are delimited by a beginning and ending tag : [!-- BEGIN nomSegment --][!-- END nomSegment --].
The result
tutorial odtPHP
Note : the texts in the PHP code are shorter than the result in order to make it more readable. Styles (colors, layouts) of this result come from our template.