diggindata / phpxform
PHP port of pyxform: convert XLSForms to ODK XForms.
Requires
- php: >=8.3
- ext-ctype: *
- ext-dom: *
- ext-json: *
- ext-libxml: *
- ext-mbstring: *
- ext-xmlreader: *
- ext-zip: *
Requires (Dev)
- phpunit/phpunit: ^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
PHP 8.3 library ported from the Python project pyxform (currently upstream commit 0619ec2, after release 4.5.0). It converts XLSForms (XLSX, CSV, Markdown) into ODK XForms with the same output and error messages as the Python original.
The development tools (recorder, generators) expect a checkout of pyxform in the sibling directory ../python; using the library does not.
Usage
Installation
composer require diggindata/phpxform
Requirements: PHP 8.3 or newer with the extensions ctype, dom, json, libxml, mbstring, xmlreader and zip. Checking forms with ODK Validate (optional, see below) additionally requires Java 8 or newer.
Working copy via symlink (path): Handy while you are developing the library itself next to an application. Composer symlinks the directory, so changes are visible immediately, even without a commit or tag:
{
"repositories": [
{ "type": "path", "url": "../pyxform/php" }
],
"require": {
"diggindata/phpxform": "@dev"
}
}
@dev is required here: with path, Composer follows the branch and ignores the tags. It therefore only knows the library as the development version dev-main, and "*" or "^0.1" would only accept stable versions.
Converting an XLSForm file
Xls2xform::convert() is the entry point, like pyxform.xls2xform.convert() in Python. A file (.xlsx, .xlsm, .csv, .md) is passed as a path:
use Pyxform\Xls2xform;
$warnings = [];
$result = Xls2xform::convert('/path/to/form.xlsx', warnings: $warnings);
file_put_contents('form.xml', $result->xform);
// Only for forms with an "external_choices" sheet: the choice lists as CSV,
// which must be served next to the XForm as itemsets.csv.
if ($result->itemsets !== null) {
file_put_contents('itemsets.csv', $result->itemsets);
}
foreach ($warnings as $warning) {
echo "Warning: $warning\n";
}
If the string is not an existing path, it is read as content, as in Python. So the content of an uploaded file can be passed directly as well.
Markdown or CSV content
When passing content instead of a path, fileType sets the format:
$md = <<<'MD'
| survey | | | |
| | type | name | label |
| | text | name | What is your name? |
| | integer | age | How old are you? |
MD;
$result = Xls2xform::convert(
$md,
prettyPrint: true, // Formatted XML (default: false)
formName: 'survey', // Name of the instance's root element (default: "data")
fileType: '.md', // ".md", ".csv", ".xlsx" or ".xlsm"
);
echo $result->xform;
Further parameters are defaultLanguage (the default language if it is not set in the form's settings) and validate (see below).
Form as an array
Instead of a file, an array of sheets works too, like the dict in Python. Each sheet is a list of rows, each row an array mapping column name to value:
$form = [
'survey' => [
['type' => 'select_one colors', 'name' => 'color', 'label' => 'Favourite colour?'],
],
'choices' => [
['list_name' => 'colors', 'name' => 'red', 'label' => 'Red'],
['list_name' => 'colors', 'name' => 'blue', 'label' => 'Blue'],
],
'settings' => [
['form_title' => 'Colors', 'form_id' => 'colors', 'version' => '2026111801'],
],
];
$xform = Xls2xform::convert($form)->xform;
Handling errors
Errors in the form throw a Pyxform\Errors\PyXFormError. The message is the same as in Python; for errors with a code, the enum case is in errorCode. Subclasses are PyXFormReadError (file not readable) and ValidationError.
use Pyxform\Errors\PyXFormError;
try {
$result = Xls2xform::convert($upload);
} catch (PyXFormError $e) {
// e.g. "Unknown question type 'foo'."
echo $e->getMessage();
echo $e->errorCode?->name; // null if the error has no code
}
Checking with ODK Validate
With validate: true, the generated XForm is additionally checked with ODK Validate (requires Java):
use Pyxform\Validators\OdkValidate;
use Pyxform\Validators\OdkValidate\ODKValidateError;
// Optional: use a different JAR than the bundled one.
// OdkValidate::setOdkValidatePath('/opt/odk/ODK_Validate.jar');
$warnings = [];
try {
$result = Xls2xform::convert($upload, warnings: $warnings, validate: true);
// Notices from ODK Validate are in $warnings ("ODK Validate Warnings: ...").
} catch (PyXFormError $e) {
// Error in the XLSForm
} catch (ODKValidateError $e) {
// The XForm is invalid. The message starts with "ODK Validate Errors:", e.g.
// 'Invalid calculate for the bind attached to "${bad}" : ...'
} catch (\Pyxform\Port\PyException $e) {
// $e->type === 'OSError': Java was not found.
}
// Does the installation (Java and JAR) work?
$ok = OdkValidate::installExists() && OdkValidate::installOk();
Individual intermediate steps
convert() consists of three steps that can also be called individually, e.g. to store the JSON intermediate form or to inspect the Survey object:
use Pyxform\Builder;
use Pyxform\Xls2json;
use Pyxform\Xls2jsonBackends;
// 1. Read the file or content (Python xls2json_backends.get_xlsform)
$workbook = Xls2jsonBackends::getXlsform($md, fileType: '.md');
// 2. Convert into the JSON intermediate form (Python xls2json.workbook_to_json)
$warnings = [];
$json = Xls2json::workbookToJson(
workbookDict: $workbook,
formName: 'survey',
fallbackFormName: $workbook->fallbackFormName,
warnings: $warnings,
);
// 3. Build the object model and generate XML (Python builder / Survey.to_xml)
$survey = Builder::createSurveyElementFromDict($json);
$xform = $survey->toXml(prettyPrint: false, warnings: $warnings);
convert() returns the same in its result: $result->pyxform is the JSON intermediate form, $result->survey the Survey object. As in Python, both may change without notice.
Comparison with the Python original
The reference is the behaviour of the Python version. tools/recorder/record.py runs the Python test suite without modifying the Python repo. For every call to assertPyxformXform and for every form file in tests/fixtures/{example_forms,bug_example_forms}, it records the input and the actual output:
tests/fixtures/recorded/<module>.jsoncontains the cases per Python test module.tests/fixtures/recorded/_form_files.jsoncontains the cases from files, whose copies are undertests/fixtures/files/.tests/fixtures/recorded/_manifest.jsoncontains the upstream commit, counts, and the Python tests without recorded cases. The latter have to be ported by hand.
tests/Recorded/RecordedCasesTest.php replays every case. A case passes if either of two conditions holds:
- XForm: After C14N the XML is equal, and warnings and itemsets match exactly.
- Error: Error class,
errorCode(name of the enum case) and error message match.
Cases that the Python test builds from a Survey object instead of a form are rebuilt by the test from that object's recorded to_json_dict() using the builder. Three cases are skipped because to_json_dict() already fails in Python (see below).
Currently all 1,358 successful conversions even match Python byte for byte, not just after C14N.
Intermediate stage workbook_to_json: The recorder additionally captures what workbook_to_json() returns inside convert(): the JSON intermediate form with the warnings up to that point, or that the function raised an exception (key actual.workbook_to_json). tests/Recorded/WorkbookToJsonTest.php requires Xls2json::workbookToJson() to produce the same intermediate form and the same warnings. On an error, class, errorCode and message must match. The test also checks the itemsets (has_external_choices, external_choices_to_csv).
Intermediate stage builder: Likewise, the recorder captures what the builder makes of this intermediate form: create_survey_element_from_dict(...).to_json_dict() or the error raised (key actual.builder, with stage = create or to_json_dict). It works on a deep copy so that the recorded conversion stays untouched. tests/Recorded/BuilderTest.php compares Builder::createSurveyElementFromDict() and Survey::toJsonDict() against it.
Function calls: In addition, tools/recorder/calls.py records calls to selected pure Python functions during the test run. It stores the arguments (before the call, with defaults) and the result or the error, at most 3,000 distinct calls per function. The fixtures are in tests/fixtures/calls/<module>.<function>.json. tests/Unit/RecordedCallsTest.php replays them against the PHP functions mapped in functions(). A newly ported function is therefore hooked up in two steps: add it to RECORDED_FUNCTIONS (calls.py) and map it in functions().
Ordering: In some places the Python original iterates over a set. The order of sibling elements or of lists in error messages then depends on PYTHONHASHSEED. The recorder handles this as follows:
- It records with the fixed seed
0. This keeps the fixtures stable and the diffs clean. - It then compares with seeds 1 to 5. Cases whose result changes get
"order_unstable": true. - Only for these cases does the PHP test compare regardless of order: sibling elements sorted, messages as sorted tokens.
A recording run therefore takes just under five minutes.
Known messages during recording:
setUpClass (tests.test_validator_update…)fails if port 8000 is in use locally. The validator updater is not within the scope of the port.- There are
recording_errorsfor three cases intest_case_insensitivity:Survey.to_json_dict()fails on OSM questions in the original. The XForm output of these cases is recorded nonetheless. The cause is thatOSM_QUESTION_FIELDScontains the itemset fields, whichOsmUploadQuestiondoes not have. The port reproduces thisAttributeError.
Setting up the recorder (once)
python3 -m venv tools/recorder/.venv
tools/recorder/.venv/bin/pip install --requirement ../python/pylock.dev.toml
tools/recorder/.venv/bin/pip install --no-deps --editable ../python
Pulling in upstream changes
- Update the Python repo
../python, for example withgit pull. - Regenerate the data modules with
composer generate(see below). - Regenerate the fixtures with
composer record. git diff src tests/fixturesshows every data and behaviour change. Then rungit diff <old-commit>..<new-commit>in the Python repo (_manifest.jsonnames the old commit) and adapt the affected PHP classes. The mapping follows from the conventions below.composer test
Generated data modules
Pure data is not ported by hand. tools/generate/generate.py imports the Python modules and writes them as PHP classes whose header marks them as generated. Do not edit these files by hand.
| Python | PHP |
|---|---|
pyxform/constants.py | Pyxform\Constants and the enums in Pyxform\Constants\* |
pyxform/aliases.py | Pyxform\Aliases, with the constant names from Python (e.g. Aliases::control) |
pyxform/question_type_dictionary.py | Pyxform\QuestionTypeDictionary::QUESTION_TYPE_DICT |
pyxform/errors.py (ErrorCode) | Pyxform\Errors\ErrorCode; Python ErrorCode.X.value corresponds to ErrorCode::X->value() |
pyxform/xls2json.py, pyxform/utils.py | Pyxform\Xls2json (regexes RE_*), Pyxform\Utils |
pyxform/validators/pyxform/{settings,android_package_name,translations_checks}.py | Pyxform\Validators\Pyxform\{Settings,AndroidPackageName,TranslationsChecks} |
pyxform/{survey_element,section,question,survey}.py | Pyxform\{SurveyElement,Section,Question,Survey}, e.g. the field lists Question::OPTION_FIELDS (Python Option.get_slot_names()) |
pyxform/elements/action.py (Event) | Pyxform\Elements\Action\Event |
pyxform/external_instance.py, pyxform/survey_elements/{attribute,label}.py, pyxform/entities/entity_declaration.py | Pyxform\ExternalInstance, Pyxform\SurveyElements\{Attribute,Label}, Pyxform\Entities\EntityDeclaration (field lists) |
The mapping rules are:
- Python
sets become sorted lists, because their order is meaningless. Membership is checked within_array(..., true). - Tuples become lists.
- If a generated module also has functions, these are hand-written in the trait
<Class>\ModuleFunctions, for exampleQuestionTypeDictionary\ModuleFunctions::getMetaGroup().
The generator also writes reference values to tests/fixtures/generated/. The unit tests compare against them: Python values against PHP constants, every error template formatted, and str()/repr() for Pyxform\Port\Py.
Regular expressions: Compiled Python patterns (re.compile) are generated as PCRE literals ('/.../u'). The translation in tools/generate/pyre.py makes diverging semantics explicit:
\s,\Sand\dbecome explicit character classes from Python's Unicode data, since Python counts e.g.\x1c–\x1fas whitespace.\bbecomes lookarounds on an explicit\wclass (str.isalnum()or_). Without UCP, PCRE only knows ASCII word boundaries.\uXXXXbecomes\x{...},\Zbecomes\z.- Unsupported syntax aborts generation.
Pyxform\Port\Re reproduces the Python operations: fullmatch, match, search, finditer, sub. Positions there are UTF-8 byte offsets.
lark grammars: A Lark object _X becomes _X_TERMINALS. This is the list [name, PCRE] in exactly the order in which lark tries the terminals. The parsers themselves are hand-written (Pyxform\Port\Lark\*, Parsing\*\ModuleFunctions). For verification, the generator produces corpus fixtures (tests/fixtures/generated/corpus_*.json) from all table cells of the recorded forms, the lexer test cases and Unicode edge cases. tests/Unit/Parsing/CorpusTest.php requires the same tokens, trees and errors as lark for them.
Pyxform\Port\* contains helpers for Python semantics that do not exist in the original. One example is Py::str(), which reproduces Python str() for f-strings and format().
Input formats (XLSX, CSV, Markdown)
Pyxform\Xls2jsonBackends is the port of xls2json_backends.py. getXlsform() takes a file path, the file content as a string, a stream, or an array with the fields of DefinitionData. Python distinguishes path (str) and content (bytes). PHP strings are always bytes, so a string counts as a path if a file with that name exists.
The readers follow the Python libraries down to their edge cases, not their PHP counterparts:
- XLSX:
Pyxform\Port\Openpyxlports openpyxl's read path (read_only=True, data_only=True) usingZipArchiveandXMLReader. Ported are shared strings, cell types, date detection via number formats, the 1900 and 1904 epochs, the sheet size from<dimension>and padding of missing rows. PhpSpreadsheet is not used because it handles date formats, numbers and the sheet size differently. openpyxl's built-in number formats are generated inPort\Openpyxl\Data, along with the openpyxl version. - CSV:
Pyxform\Port\Csvports the state machine of Python'scsv.reader.str_getcsv()handles quotes and backslashes differently. - Values: Dates, times and durations from XLSX cells are
Port\Datetime\{Date, Time, DateTime, Timedelta}. Integers outside PHP's range arePort\BigInt. This makes text and rounding match Pythonstr(), even fortimedeltafrom floats.
Not ported are convert_file_to_csv_string, sheet_to_csv, xlsx_sheet_to_csv and md_table_to_workbook. These are helpers for tests and the command line that write files.
Fixtures: tools/generate/backends_fixtures.py (part of composer generate) records, for every input, what get_xlsform() returns, with and without a file type. It stores the DefinitionData fields or the error. The inputs are:
- the form files of the Python tests, as path and as content;
- all recorded Markdown forms and
ss_structuredicts; - purpose-built XLSX packages under
tests/fixtures/generated/xlsx/: cell types, number formats, about 500 date serial numbers per epoch, sheet sizes, package structure and error cases; - CSV and Markdown edge cases.
tests/Unit/Xls2jsonBackendsTest.php compares against them. tests/Unit/Port/CsvTest.php additionally compares Csv::reader() with csv.reader on about 1,300 random strings.
JSON intermediate form (xls2json)
Pyxform\Xls2json::workbookToJson() is the port of workbook_to_json(). This includes the validators under Pyxform\Validators\Pyxform\*, Pyxform\Entities\EntitiesParsing and Pyxform\Elements\Action\ActionLibrary. The result is a nested array with the same keys as the Python dict. entity_version is the enum case Constants\EntityVersion.
Shared data: Python dicts and lists are objects. In some places workbook_to_json relies on several places holding the same object. Example: an or_other question appends "other" to a choices list, and earlier questions with the same list see that too. The port uses PHP references (&) for this and resolves them with Py::deref() before returning. Affected are the child list of the current container, choices lists (in questions, columns of loops, table-list headers and json_dict["choices"]) and OSM tags.
Numbers: The range validator computes with decimal.Decimal in Python. Pyxform\Port\Decimal reproduces the required parts without bcmath or gmp: parsing (with Unicode digits and underscores), comparisons, subtraction and remainder with 28 digits of precision, isinf() via float, and the errors InvalidOperation and Overflow.
Fixtures: tools/generate/xls2json_fixtures.py produces additional reference cases that the upstream tests do not cover. These include shared choices and OSM tags, numeric list and choice names, and Decimal edge cases. It also produces fuzz cases for Decimal and the path functions (os.path.splitext, pathlib suffixes). The corresponding tests are tests/Unit/Xls2jsonTest.php, tests/Unit/Port/DecimalTest.php and tests/Unit/Port/PyTest.php.
Object model and builder
Pyxform\Builder::createSurveyElementFromDict() builds the object model from the JSON intermediate form: Survey\Survey, Section\{GroupedSection,RepeatingSection}, Question\* (with Option, Itemset, Tag), ExternalInstance\ExternalInstance, Entities\EntityDeclaration\EntityDeclaration and SurveyElements\{Attribute,Label}. Not ported are the builder functions that read files (create_survey_from_xls, create_survey_from_path, create_survey_element_from_json).
- Slots: The Python slots are public properties with the Python names (
$question->list_name,$survey->id_string). This lets the generated field lists (Question::QUESTION_FIELDSetc.) address them, as Python does viaself[key]. For this there aregetItem(),setItem()andhasAttr(). A field the class does not have raises anAttributeError, as in Python. The parent is set withsetParent(), because Python clears the XPath cache when doing so. - `kwargs
:** The constructors receive the dict of Python keyword arguments as an array and take their named parameters from it withPort\Kwargs::pop()orKwargs::required(). Whatever remains ends up inextra_data`, as in Python. - Loops:
_name_and_label_substitutionsformats the templates with Python'sstr % mapping.Pyxform\Port\PercentFormatreproduces this (%(key)s,r,a,d,i,u, flags, width, precision, error messages). - Deviation: With the setting
add_none_option, Python appends the choice "none" to the choices list of aselect_all_that_applyquestion. If several questions share this list, the later ones get no "none" constraint in Python. The PHP builder treats each question on its own. Upstream does not test this setting.
Fixtures: tools/generate/builder_fixtures.py feeds dicts directly to the Python builder: add_none_option, include, loops with unusual templates and error paths. It also produces reference cases for str % mapping. The corresponding tests are tests/Unit/BuilderTest.php and tests/Unit/Port/PercentFormatTest.php.
XML output
Xls2xform::convert() returns the ConvertResult with xform, warnings and itemsets, plus (like Python _pyxform/_survey) pyxform and survey. The XForm is produced by Survey::toXml().
- minidom: Python builds the XML with
xml.dom.minidomand its ownwritexml()methods. The port reproduces the part in use inPyxform\Utils\{XmlNode,DetachableElement,Text,Attr}: attribute order,setAttributeNode(),appendChild()moving nodes,toxml()andtoprettyxml(). The output is therefore byte-for-byte identical even when pretty-printed. node():Utils::node($tag, ...$children, attr: $value)corresponds to Pythonnode(tag, *args, **kwargs). Attribute names that are not PHP identifiers are passed as an array:...['odk:prefix' => $p].- Positions: Regex matches (
Port\ReMatch) and substrings work with UTF-8 byte offsets. Length checks such aslen(text) < 3count characters (mb_strlen). - Sets: Where Python iterates over a
set(e.g. missing translations in_add_empty_translations), the port uses insertion order. - ODK Validate:
Survey::toXml()defaults tovalidate: false, unlike Python (see below). - IANA language codes:
generate.pycopies the lists fromiana_subtags/tosrc/Validators/Pyxform/IanaSubtags/.
Fixtures: The recorded cases convert without pretty-printing. tools/generate/xform_fixtures.py takes every 20th recorded Markdown form and produces the pretty-printed Python output for it. tests/Unit/XformPrettyTest.php compares it byte for byte.
ODK Validate
Optionally, Xls2xform::convert($form, validate: true) checks the XForm with ODK Validate. This requires Java 8 or newer on the PATH.
- An invalid XForm throws
Validators\OdkValidate\ODKValidateError. As in Python, this is not aPyXFormError; the message is cleaned up withErrorCleaner. - Notices from Validate end up in
$warnings. - If Java is missing, a
PyExceptionof typeOSErroris thrown. - The JAR file (
src/Validators/OdkValidate/bin/) and the test form forinstallOk()are copied from upstream bycomposer generate. Upstream also keeps the JAR in Git.OdkValidate::setOdkValidatePath()sets a different JAR. - Not ported: the updater (
updater.py),request_get()and the Windows special cases when starting the process.
composer test:odk-validate (suite tests/OdkValidate) checks the PHP XForm of all recorded cases for which the Python test runs ODK Validate or expects a Validate error. Without Java the suite is skipped. The cases for ErrorCleaner are produced by tools/generate/validator_fixtures.py.
Porting conventions
The structure mirrors Python 1:1 so that upstream diffs can be mapped to individual files.
- Module functions: The Python module
pyxform/a/b.pybecomes the PHP classPyxform\A\B. Its module-level functions become static methods of this class. - Classes: A class
Foodefined inpyxform/a/b.pybecomesPyxform\A\B\Foo. This also applies to the object model:pyxform/question.pybecomes the module classPyxform\Question(data and functions), the classOptionin it becomesPyxform\Question\Option. - Sets: A local Python
setof strings becomes an array with the values as keys ($seen[$name] = true,isset($seen[$name])). PythonCounterbecomes an array mapping name to count. - Names: Methods and parameters are written in camelCase, with the same order and meaning as in the original (for example
form_name→formName). - Python semantics: For strings, use
Py::strip(),Py::split(),Py::isspace(),Py::lower()andPy::len()instead oftrim(),explode()andstrlen(). Truthiness is checked withPy::bool(), because"0"is false in PHP but true in Python. - Dict keys: PHP turns numeric string keys (
"1") into integers. Keys from user data (column headers, choice names, parameters) are converted back with(string)when read. A Python keyNone(e.g. for a cell without a column header) becomesPy::NONE_KEY, a keyFalsebecomesPy::FALSE_KEY. - Python exceptions: Where the original catches built-in exceptions by class (e.g.
except (KeyError, TypeError)), the port throwsPyxform\Port\PyExceptionwith the Python class name in$typeand checks it withisAny(). Exceptions the original does not catch also propagate asPyExceptionin PHP. One example is theKeyErrorfor a CSV sheet name without content. - Errors: Python
raise PyXFormError(msg, code=X, context={...}) from ecorresponds tothrow new PyXFormError($msg, errorCode: ErrorCode::X, context: [...], previous: $e). The parameter is callederrorCodebecauseException::$codeis already taken as an integer in PHP. Python code that modifiese.contextafterwards uses$e->updateContext([...]). This regenerates the message, becausegetMessage()isfinalin PHP.
License
Derived from pyxform, Copyright (c) 2015, XLSForm. See LICENSE.