Tutorial 4 : Imbricate several segments - neeftarah/odtphp GitHub Wiki

The purpose of this tutorial is to show how to imbricate several segments within others segments. Imbricating segments is a very simple task with odtPHP.

The PHP code

<?php
require_once('../library/odf.php');

$odf = new odf("tutoriel4.odt");

$odf->setVars('titre','Articles disponibles :');

$categorie = $odf->setSegment('categories');
for ($j = 1; $j <= 2; $j++) {
    $categorie->setVar('TitreCategorie', 'Catégorie ' . $j);
    for ($i = 1; $i <= 3; $i++) {
        $categorie->articles->titreArticle('Article ' . $i);
        $categorie->articles->date(date('d/m/Y'));
        $categorie->articles->merge();
    }
    for ($i = 1; $i <= 4; $i++) {   
        $categorie->commentaires->texteCommentaire('Commentaire ' . $i);
        $categorie->commentaires->merge();        
    }
    $categorie->merge();
}
$odf->mergeSegment($categorie);

$odf->exportAsAttachedFile();
 
?>
  1. We create an Odf object by specifying the path to our template. Then, we call the method setVars() of the created object in order to replace the tag {titre} by text content.

  2. We initialize the segment "categories" with a call to the method setSegment() which takes for argument the name of the segment and returns an object of type Segment.

  3. For this example, we want to add to the generated document two categories. So, we loop a first time from 1 to 2. At each loop, we indicate a title to our current category with a call to the method setVar().

  4. In the loop, each child segment is accessible through the property of the same name of the father segment. For instance, the segment "articles" is a child of segment "categories". So, we can access to it directely with $categorie->articles. Thus, we can replace variables of this child segment with the method that has the same name of the tag to replace. For instance : $categorie->articles->titreArticle(). Alternatively, we can also call the method setVar() which will perform the same replacement.

  5. For each child and for the segment "categories", we call the method merge() in order to merge data for each loop. Only one call to mergeSegment() is required at the end to add all our segments to the generated document.

The OpenOffice model (tutoriel4.odt)

{titre}

[!-- BEGIN categories --]
{TitreCategorie}

Articles :
[!-- BEGIN articles --]
- {titreArticle}
Date de publication : {date}[!-- END articles --]

Commentaires :
[!-- BEGIN commentaires --]
Texte : {texteCommentaire}[!-- END commentaires --]
[!-- END categories --]

To run this example, copy this template within an OpenOffice document named "tutoriel4.odt". In the template, we can imbricate segments easily. The segment "categories" contains a segment "articles" and another segment "commentaires".

The result

tutorial odtPHP

Styles (colors, layouts) of this result come from our template.