Voici une classe extrêmement simple pour manipuler un fichier Writer OpenOffice.
<?php
class odfDoc{
private $file; // File name
private $content; // File content extracted from the content.xml file
private $vars = array(); // Array with all the data to change
function odfDoc($file) {
$this->file = $file;
$zip = new ZipArchive();
if ($zip->open($this->file) === TRUE) {
$this->content = $zip->getFromName('content.xml');
$zip->close();
} else {
exit("Error while Opening the file '$file' - Check your odt file\n");
}
}
function setVars($key, $value) {
$this->vars[$key] = $value;
}
function parse() {
if ($this->content != NULL) {
$this->content = str_replace(array_keys($this->vars), array_values($this->vars), $this->content);
} else {
exit("Nothing to parse - check that the content.xml file is correctly formed\n");
}
}
function printVars() {
echo '<pre>';
print_r($this->vars);
echo '</pre>';
}
function save($newfile) {
if ($newfile != $this->file){
copy($this->file, $newfile);
$this->file = $newfile;
}
$zip = new ZipArchive();
if ($zip->open($this->file, ZIPARCHIVE::CREATE) === TRUE) {
if (!$zip->addFromString('content.xml', $this->content))
exit('Error during the file saving');
$zip->close();
} else {
exit('Error during the file saving');
}
}
}
?>
Pour y faire appel il faut avoir le fichier odt dans le répertoire courant. Dans ce fichier il faut indiquer les variables à remplacer par {variable1}. Voici un exemple d'utilisation :<?php
require("odfDoc.php");
$odf = new odfDoc("fichierTemplate.odt");
$odf->setVars("{titre1}", "Formation PHP Expert");
$odf->setVars("{titre2}", "Objectifs");
$odf->parse2();
$odf->save("fichierResultat.odt");
?>