A PHP library for creating and manipulating ODT (OpenDocument Text) files.
- PHP 8.1 or higher
- PHP ZIP Extension or PclZip library. PHP ZIP Extension is recommended as we will probably remove the PclZip library sometime in the future.
Install via Composer:
composer require sboden/odtphp:^4<?php
use Odtphp\Odf;
// Create a new ODT document from a template
$odt = new Odf("template.odt");
// Set simple text variables
$odt->setVars('company_name', 'ACME Corporation');
$odt->setVars('current_date', date('Y-m-d'));
// Save the modified document
$odt->saveToDisk('output.odt');<?php
use Odtphp\Odf;
// Create ODT document with custom configuration
$config = [
'DELIMITER_LEFT' => '{',
'DELIMITER_RIGHT' => '}',
];
$odt = new Odf("invoice_template.odt", $config);
// Insert a company logo
$odt->setImage('company_logo', 'path/to/logo.png');
// Create a repeatable segment for line items
$lineItems = $odt->setSegment('invoice_items');
foreach ($invoiceData['items'] as $item) {
$lineItems->setVars('item_name', $item->name);
$lineItems->setVars('item_price', number_format($item->price, 2));
$lineItems->setVars('item_quantity', $item->quantity);
$lineItems->merge();
}
// Set summary variables
$odt->setVars('total_amount', number_format($invoiceData['total'], 2));
$odt->setVars('invoice_number', $invoiceData['number']);
// Save the completed invoice
$odt->saveToDisk('invoice.odt');You can update custom document properties in your ODT file using the updateCustomProperty() method:
$odf->updateCustomProperty('Author', 'John Doe');
$odf->updateCustomProperty('Version', '1.0');Important notes about custom properties:
- It's recommended to use only strings for custom properties. The reason is that the value will be replaced by odtphp, but the value is supposed to be in the internal format as defined by odt for that particular type. Odtphp only replaces the value of the custom property, odtphp will not do data conversions.
- For dates e.g., make sure to use YYYY-MM-DD as format as that is what ODT wants as internal date format.
- Special characters will be HTML encoded by default.
- Properties must exist in the document before they can be set.
- Setting custom properties works when using LibreOffice/OpenOffice only. It seems to fail using Microsoft Word as Microsoft Word does not update the custom property values upon opening an ODT file.
- Newlines are not supported in custom property values because the LibreOffice GUI does not allow newlines. updateCustomProperty() will happily insert newlines and the newlines will also be outputted, but this "unofficial" functionality which may be blocked in the future by ODT.
Examples:
// Basic string properties
$odf->updateCustomProperty('Author', 'John Doe');
$odf->updateCustomProperty('Department', 'Engineering');
// Dates should use YYYY-MM-DD format
$odf->updateCustomProperty('Creation Date', '2024-01-20');
// Special characters are encoded by default
$odf->updateCustomProperty('Note', '<important> & urgent'); // Will be encoded
$odf->updateCustomProperty('Note', '<important> & urgent', FALSE); // Won't be encodedYou can insert images into your ODT file using different measurement units:
// Using centimeters (original function)
$odf->setImage('logo', 'path/to/logo.png', -1, 5, 7.5); // 5cm width, 7.5cm height
$odf->setImage('photo', 'path/to/photo.jpg', 1, 10, 15, 2, 2); // On page 1 with 2cm offsets
// Using millimeters
$odf->setImageMm('logo', 'path/to/logo.png', -1, 50, 75); // 50mm width, 75mm height
$odf->setImageMm('photo', 'path/to/photo.jpg', 1, 100, 150, 20, 20); // On page 1 with 20mm offsets
// Using pixels (automatically converts to mm)
$odf->setImagePixel('logo', 'path/to/logo.png', -1, 189, 283); // 189px ≈ 5cm, 283px ≈ 7.5cm
$odf->setImagePixel('photo', 'path/to/photo.jpg', 1, 378, 567, 76, 76); // On page 1 with 76px offsets
// Keep original image size
$odf->setImage('icon1', 'path/to/icon.png'); // Will convert to cm
$odf->setImageMm('icon2', 'path/to/icon.png'); // Will convert to mm
$odf->setImagePixel('icon3', 'path/to/icon.png'); // Will keep original pixel dimensionsParameters for all image functions:
$key: Name of the variable in the template$value: Path to the image file$page: Page number (-1 for as-char anchoring)$width: Width in respective units (null to keep the aspect ratio, or the original size when$heightis also null)$height: Height in respective units (null to keep the aspect ratio, or the original size when$widthis also null)$offsetX: Horizontal offset (ignored if $page is -1)$offsetY: Vertical offset (ignored if $page is -1)
Each image file gets one name in Pictures/ of the document. Two different files
with the same name (a/logo.png and b/logo.png) are saved as logo.png and
logo-2.png, and a new image never replaces a picture of the template.
Note: While setImagePixel accepts measurements in pixels, the ODT format requires millimeters or
centimeters internally. The function automatically converts pixel measurements to the appropriate
format.
<?php
use Odtphp\Odf;
use Odtphp\Exceptions\OdfException;
try {
$odt = new Odf("template.odt");
// This will throw an exception if the variable doesn't exist
$odt->setVars('non_existent_variable', 'Some Value');
} catch (OdfException $e) {
// Handle template-related errors
error_log("ODT Processing Error: " . $e->getMessage());
}- Install dependencies:
composer install
- Run the tests:
On Linux:
# Go to the root of odtphp, then:
./run-tests.shOn Windows:
# Go to the root of odtphp, then:
run-tests.bat
# Note that depending on your PHP installation you may have to edit the
# script to include the path to php.exeYou can also run the PHPUnit tests e.g. in PHPStorm, but you have to exclude the vendor directory to avoid warnings about the PHPUnit framework itself.
run-tests-multi-php.sh runs the test suite inside Docker containers for one
or more PHP versions. Docker must be installed and running.
# Test all supported versions (8.1, 8.2, 8.3, 8.4)
./run-tests-multi-php.sh
# Test a single version
./run-tests-multi-php.sh 8.1
# Test several specific versions
./run-tests-multi-php.sh 8.2 8.4
# Force a rebuild of the Docker test images (e.g. after a PHP release)
./run-tests-multi-php.sh --rebuild
# Pass extra arguments through to PHPUnit
./run-tests-multi-php.sh -- --display-deprecations
./run-tests-multi-php.sh 8.3 -- --testdoxDocker images are built once per PHP version and cached locally as
odtphp-test:phpX.Y, so subsequent runs are fast. Each container runs
composer update to resolve packages that are compatible with the PHP version
under test, which ensures the correct dependency versions are used across the
full supported range (PHP 8.1 through 8.5+).
The test suite covers various aspects of the ODT templating functionality:
-
Basic Tests (
Basic1Test.phpandBasic2Test.php):- Verify basic variable substitution in ODT templates
- Test both PhpZip and PclZip ZIP handling methods
- Demonstrate simple text replacement and encoding
-
Configuration Tests (
ConfigTest.php):- Validate configuration handling
- Test custom delimiters
- Check error handling for invalid configurations
-
Edge Case Tests (
EdgeCaseTest.php):- Handle complex scenarios like:
- Large variable substitution
- Nested segment merging
- Special character encoding
- Advanced image insertion
- Invalid template handling
- Handle complex scenarios like:
-
Image Tests (
ImageTest.php):- Verify image insertion functionality
- Test image resizing
- Check error handling for invalid image paths
-
Variable Tests (
VariableTest.php):- Test variable existence checks
- Verify special character handling
- Check multiline text substitution
-
Custom Property Test (
SetCustomPropertyTest.php):- Test custom propertyfunctionality
Each test is designed to ensure the robustness and reliability of the ODT templating library across different use cases and configurations.
A lot of tests run twice:
- Once using PclZip library
- Once using PHP's native Zip extension
The tests generate ODT files and compare them with gold standard files located in:
tests/src/files/gold_phpzip/- Gold files for PHP Zip teststests/src/files/gold_pclzip/- Gold files for PclZip tests
On Linux:
# Go to the root of odtphp, then:
composer install
vendor/bin/phpcs --standard="Drupal,DrupalPractice" -n --extensions="php,module,inc,install,test,profile,theme" src- Template variable substitution
- Image insertion and manipulation
- Segment management for repeatable content
- Support for custom delimiters
- Type-safe implementation
- Modern PHP 8.1+ features
$config = [
'ZIP_PROXY' => \Odtphp\Zip\PhpZipProxy::class, // or PclZipProxy
'DELIMITER_LEFT' => '{',
'DELIMITER_RIGHT' => '}',
'PATH_TO_TMP' => '/tmp'
];
$odt = new Odf("template.odt", $config);This library is built with PHP 8.1's type system in mind:
- Strict typing enabled
- Property type declarations
- Return type declarations
- Parameter type hints
- Improved error handling
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the GPL-3.0 License - see the LICENSE file for details.
The GPL-3.0 license is because of what the cybermonde/odtphp author put it to, I (sboden) don't want to change it. I don't consider odtphp to be "my" software, I only tried to make the cybermonde/odtphp fork work properly in PHP v8.3 and beyond.
Personally (sboden) I would have used an MIT or BSD license for odtphp, but I will happily abide with the original author's intent.
The original version/source code of odtphp is at https://sourceforge. net/projects/odtphp/. The cybermonde/odtphp fork I started from is at https://github. com/cybermonde/odtphp.
How and why we use odtphp in our projects.
Some of our projects send out letters (either PDF or on physical paper) to people: the idea is to have a nice template, fill in some data, create a PDF file from the filled-in template, and send the resulting PDF to the recipient.
The template is an ODT file, the data is stored in a database. We use odtphp to fill in the template. The filled-in ODT file is then transformed into a PDF file using (originally) jodconverter, and in newer projects gotenberg.dev (which is essentially "jodconverter in golang"). The PDF converters run in a different container than the main applications.
The reason for using gotenberg over jodconverter is that gotenberg is better supported. Main problem with gotenberg is the quantity of PDFs. In a customised jodconverter we run multiple threads at the same time in one docker container to generate about 50,000 PDFs daily (10K per hour); with gotenberg you would have to run multiple docker containers to generate those the same amount of PDFs in the same timespan.
Why not generate PDFs directly from PHP? We tried, but it's difficult to have nice-looking PDFs using the existing PHP libraries. One PHP library has problems with images, another PHP PDF library faces issues with margins and headers/footers, ... We tried a lot of different setups and finally settled for odtphp/gotenberg to have the PDF output "pixel perfect".
Because LibreOffice adds metadata to text that you change. E.g. when you have something as follows in your ODT file:
{variable_text}
And you make a small change to the previous text it may very well end up as:
{variable<text:span text:style-name="T4">s</text:span>_text}]
where you don't see the "text:span" part visually, but it is there.
odtphp repairs the variables and segment markers that are split by
<text:span>, <text:bookmark> and <text:soft-page-break/> when it opens
the template: the markup is moved after the tag. Other markup in a tag still
prevents the match.
How to get around that: When you change variable texts, select the variable text (including the begin and end delimiters), copy it, and then use "Paste special/Paste unformatted text" to copy the text in the same place without any invisible metadata.
ODT files support two different ways to insert dynamic content: variables and custom properties.
Variables are an ODTPhp feature that works by replacing text anchors (like {variable_name}) with new content:
$odf->setVars('company_name', 'ACME Corporation');
$odf->setImage('logo', 'path/to/logo.png', -1, 50, 75); // 50mm width, 75mm heightKey points about variables:
- Variables are specific to ODTPhp, variables are not a feature of the ODT specification
- Work as simple text replacements in the document
- Support images through
setImage,setImageMm, andsetImagePixelfunctions - Can be affected by LibreOffice's invisible metadata when editing the template (see previous topic)
- Must be surrounded by delimiters (default:
{and}) - Can be used anywhere in the document text
Custom properties are an official ODT feature for storing (usually) metadata about the document:
$odf->updateCustomProperty('Author', 'John Doe');
$odf->updateCustomProperty('Version', '1.0');Key points about custom properties:
- Official ODT feature supported by all ODT-compatible software
- Stored in the document's meta.xml file
- Not affected by LibreOffice's invisible metadata
- Must exist in the document before they can be set
- Cannot be used with image functions
- Must be created through the LibreOffice GUI (File > Properties > Custom Properties)
When to use which:
-
Use variables for:
- Any text content in the document body
- Images and other media
- Dynamic content that needs formatting
- Repeatable segments
-
Use custom properties for:
- Small single line text fields: name, address line 1, address line2, postal code, city, ...
Usually this is a double-encoding problem. When UTF-8 text is encoded again
as UTF-8, special characters like 'é' can appear as 'é'. This typically
happens when the text is already in UTF-8 but gets encoded again.
While setting variables you can specify the encoding as needed, e.g. as:
$categorie->setVars('TitreCategorie', 'Catégorie 1', true, 'UTF-8');One of the "major" changes I made is to put UTF-8 as the default charset when setting variables. Before the default was ISO-8859-1, but UTF-8 currently makes more sense to me.
I always recommend using UTF-8 internally within the application and handling encoding/decoding at the boundaries.
While it is a breaking change, as long as you only use odtphp and don't use
any of its internals you should be fine by just upgrading the odtphp library
to v3.
If you inherit from Odf or you use some internal things in the odtphp library, then all bets are off.
The odtphp project was initially started by Julien Pauli, Olivier Booklage, Vincent Brouté and published at http://www.odtphp.com (the website no longer exists).
As DXC Technology working for the Flemish government we started using
the cybermonde/odtphp fork (source)
in a couple of projects to fill in template ODT files with data, then transforming
the filled-in ODT to PDF using gotenberg.
We ran into a couple of problems with the cybermonde/odtphp library for
which it was easier to just create my own fork, hence sboden/odtphp: we
sometimes generate 50,000 forms daily, and cybermonde/odtphp would
occasionally overwrite outputs when processing a lot of ODT files
simultaneously (because of non-random random numbers).
Why do I try to keep this "corpse" alive? Simply because I found no replacement for it. The projects I work that use odtphp are now (= end 2024) on PHP 8.2 moving to PHP 8.3, and some pieces of the original odtphp library are starting to spew warnings. During my 2024 Christmas holidays I was writing some unit test cases for odtphp, and while testing the AI tool "Windsurf", I tried to have Windsurf automatically update odtphp to a newer PHP version, and sboden/odtphp v3 is the result of that (after some extra manual human changes).
While this fork sboden/odtphp is not officially supported, maintenance
and bug fixes are provided on a best-effort basis. The sboden/odtphp library
is actively used in production applications with planned lifecycles extending
to at least 2030.
This software is not by DXC Technology, else it would have been called
dxc/odtphp. This software is not by the Flemish government, else it
would probably have been called vo/odtphp. I have always worked on odtphp
during my personal time.
If you only use sboden/odtphp and don't poke around in its internal structures, you should be fine simply replacing v3 with v4. The main reason for introducing v4 is that you have to consciously do the upgrade, and you have to test.
Quick upgrade checklist:
- Update the constraint in your
composer.jsonto"sboden/odtphp": "^4.0"and runcomposer update sboden/odtphp. - Replace every direct read of
$segment->manifestVarswith$segment->getManifestVars(). - Replace calls to
setCustomProperty()withupdateCustomProperty()(the old name still works, but it is deprecated). - If your code reads the temporary ODT file between calls, call
saveToDisk()first:updateCustomProperty()no longer writes to the file directly. - If you extend
OdforSegment, read "Subclassers only" below. - Generate your documents with your own templates and compare the output with the v3 output.
The full list of changes follows.
Breaking changes — action required:
-
Segment::$manifestVarsis nowprotected. In v3 this property waspublic, so direct reads like$segment->manifestVarswill cause a fatal error. Replace with the new getter:// v3 foreach ($segment->manifestVars as $val) { … } // v4 foreach ($segment->getManifestVars() as $val) { … }
-
setCustomProperty()is now deferred, like all other setters. In v3 it wrote the change directly to the ZIP file on every call. In v4 the change is held in memory and flushed to disk when you callsaveToDisk()orexportAsAttachedFile()— consistent withsetVars(),setImage(), and all other setters. Code that relied on the immediate side-effect (e.g. inspecting the tmpfile between calls) must now save first. -
Image path handling changed for paths without a directory separator.
setImage(),setImageMm(), andsetImagePixel()now usebasename()/pathinfo()instead ofstrrchr()/strtok(). Paths like"logo.png"(no/) now work correctly; paths with a slash produce identical results.
Non-breaking changes worth knowing:
setVars()andsetVariable()formally declarestring|null $value. Passingnullwith encoding enabled yields an empty string, unchanged from v3.setVars($key, null, false)— passingnullwith$encode=FALSEnow also coerces to an empty string in bothOdf::setVarsandSegment::setVarsinstead of throwing aTypeError. Previously only the encoding path handled null correctly.setImagePixel()width/height are declaredfloat|null(were untyped). Passing float pixel counts like188.97now works without a TypeError.getConfig()return type corrected tomixed(was incorrectlystring). It still returnsfalsefor unknown keys — callers checking=== falseare unaffected.- Image MIME types in
META-INF/manifest.xmlnow come from the image content (getimagesize()), not from the file extension:photo.jpgis declared asimage/jpeg(wasimage/jpg), and images without an extension work. - Manifest image entries are now inserted before the closing manifest tag, with
the namespace prefix of the template's manifest (
manifest:or another one). If the manifest has no closing tag, saving throws anOdfException(before, the images were silently not declared). - Two image files with the same name no longer overwrite each other in
Pictures/: the second one is saved asname-2.ext. A new image never replaces a picture of the template. - When only the width or only the height of an image is given, the other one
keeps the aspect ratio (before, the XML got an empty size such as
svg:height="cm"). For page anchoring, a null offset is now0. Odf::setImage()accepts floats for the width, the height and the offsets (int|float|null, wasint|null).- The
setImage*()methods check that the variable exists before they register the image, so a failed call no longer leaves an unused image in the document. - Variables and segment markers that LibreOffice splits with
<text:span>, bookmarks or soft page breaks are repaired when the template is opened (new classOdtphp\TemplateCleaner). - A template without
meta.xmlcan be opened (meta.xmlis optional in ODF).customPropertyExists()returnsfalseandupdateCustomProperty()throws anOdfExceptionfor such a template. - Segments are no longer read from an HTML-decoded copy of the content XML, so
&amp;or&lt;in the static text of a segment stays escaped (before, the merged XML could be malformed). A segment name that is written with HTML entities in the template no longer matches.
Correctness fixes:
setCustomProperty()andcustomPropertyExists()now useDOMDocument+ XPath to locate<meta:user-defined>elements. The previous regex requiredmeta:nameto appear in a specific position among the element's attributes; attribute ordering is no longer significant.- Calling
saveToDisk()orexportAsAttachedFile()more than once on the sameOdfinstance no longer produces duplicate image entries inMETA-INF/manifest.xml.saveInternal()now works from a local copy of the manifest XML so$this->manifestXmlis never mutated. exportAsAttachedFile()now sends an RFC 5987filename*=UTF-8''…header alongside the ASCIIfilename=""fallback. Filenames that contain accented characters, spaces, or other non-ASCII content are transmitted correctly to modern browsers; legacy clients still receive the sanitised ASCII name.setImage(),setImageMm(), andsetImagePixel()(in bothOdfandSegment) no longer suppress PHP warnings with@when callinggetimagesize(). Errors now surface through normal PHP error-handling channels; the failing path is included in theOdfExceptionmessage.
Performance improvements (transparent):
moveRowSegments()rewired to a singlepreg_replace_callbackpass — was a nestedpreg_match_all+ per-rowpreg_matchloop.- Segment image files are batch-added inside
saveInternal()instead of opening and closing the ZIP archive on everymerge()call.
Subclassers only:
Segmentno longer has a$file(ZIP handler) property; remove any references to it in subclasses.- All
Segmentproperties ($xml,$xmlParsed,$name,$children,$vars,$manifestVars,$images) are now fully typed — subclasses that redeclare them must use compatible types. Segment::$odfis now declaredprotected Odf $odfinstead of the untypedprotected $odf. Subclasses that redeclare the property must useOdfor a compatible type.Segment::__construct()now enforcesstring $name, string $xml, Odf $odf. Any call that previously relied on implicit type coercion for these parameters will now raise aTypeError.Odf::initializeProperties()removed (was dead code duplicating property defaults already set at declaration).
New tooling:
Dockerfile.testandrun-tests-multi-php.shadded for running the test suite against PHP 8.1 – 8.6 via Docker without changing the host environment.
Deprecations (soft — still callable, removed in a future version):
-
setCustomProperty()renamed toupdateCustomProperty().setCustomProperty()is kept as a deprecated pass-through alias and will be removed in a future release. Update call sites now:// deprecated $odf->setCustomProperty('Author', 'John Doe'); // use instead $odf->updateCustomProperty('Author', 'John Doe');
The rename makes the semantics explicit: the property must already exist in the document — it is updated, not created.
-
Odf::mergeAndValidateConfig()replaced bymergeConfig(). This is aprivatemethod, so it only affects subclasses that called it via reflection. The newmergeConfig()usesarray_replace()rather than a manualforeachloop and drops the misleading "validate" label (actual validation still happens invalidateTemporaryDirectory()andvalidateZipProxy()).mergeAndValidateConfig()now delegates tomergeConfig()and carries a@deprecatedtag; remove any reflection-based calls that target it.
There should be no issues upgrading; only new functionality and small bugfixes were added.
- v4.0.0 - 01Dec2026: Code quality, correctness, and performance pass, including a null-safe Odf::recursiveHtmlspecialchars() (see upgrade plan above for the full change list)
- v3.2.0 - 24Mar2025: Introduction of customPropertyExists()
- v3.1.0 - 21Mar2025: Introduction of functions setCustomProperty()/setImageMm()/setImagePixel()
- v3.0.3 - 29Dec2024: Odtphp version for PHP 8.x
- v2.2.1 - 07Dec2022: Parallel processing by odtphp does not overwrite outputs
This software is provided "as is" without warranty of any kind, either expressed or implied. The entire risk as to the quality and performance of the software is with you.
In no event will the authors, contributors, or licensors be liable for any damages, including but not limited to, direct, indirect, special, incidental, or consequential damages arising out of the use or inability to use this software, even if advised of the possibility of such damage.
By using this software, you acknowledge that you have read this disclaimer, understand it, and agree to be bound by its terms.
- http://sourceforge.net/projects/odtphp/ Sourceforge Project of the initial library (stale)