Templating — merging data with structure to produce content — is the core of front-end work. PHP offers several ways to do it. Inline interpolation inside double-quoted strings (echo "Hello, {$name}"), plain concatenation, printf, Heredoc blocks for multiline strings, and PHP tags sprinkled directly in HTML all work. The trouble starts when the logic gets heavy: compound markup such as a form or a navigation tree can nest arbitrarily, and string-building does not scale to it.
The cost of string spaghetti
Look at how WordPress Core builds a nav menu in class-walker-nav-menu.php: a single $output string that gets appended to over and over.
<?php // class-walker-nav-menu.php
// ...
$output .= $indent . '<li' . $id . $class_names . '>';
// ...
$item_output = $args->before;
$item_output .= '<a' . $attributes . '>';
$item_output .= $args->link_before . $title . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
// ...
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
// ...
$output .= "</li>{$n}";
That code has one fixed order of operations. Adding an attribute to the <a> requires $attributes to exist before the block runs. Optionally nesting a <span> or an <img> inside the link means rewriting the middle of the block with several new lines. Do both, conditionally, and you need three if statements on top — legibility gone.
The root cause is a mismatch of mental models. Developers don't think in strings when reasoning about HTML; they think in a tree of elements, each with attributes and children. Strings are merely what PHP emits and the browser consumes.
Building HTML as a tree
PHP 5 introduced the DOM module. Its entry point, DOMDocument, deliberately mirrors the JavaScript DOM API, so anyone who has used document.createElement or jQuery's $('<p>Hi there!</p>') will feel at home.
The workflow is short: instantiate the document, create an element by tag name, assign attributes, append children, and finally serialize.
$dom = new DOMDocument();
$p = $dom->createElement('p');
The tag name is a plain string — 'div', 'img' and so on all work. Attributes and children follow:
$p->setAttribute('class', 'headline');
$span = $dom->createElement('span', 'This is a headline'); // The 2nd argument populates the element's textContent
$p->appendChild($span);
Then, once the structure is complete, the string is produced in one call:
$dom->appendChild($p);
$htmlString = $dom->saveHTML();
echo $htmlString;
Note that this "document" need not represent a full page; a fragment of HTML is fine. Because saveHTML() is non-destructive, the same document can be serialized, modified further, and serialized again into a different string.
Worked example: a CRM-driven form
Suppose the server must build a form from field definitions supplied by a CRM API plus local markup. The representative response (not tied to any specific vendor) looks like this:
{
"submit_button_label": "Submit now!",
"fields": [
{
"id": "first-name",
"type": "text",
"label": "First name",
"required": true,
"validation_message": "First name is required.",
"max_length": 30
},
{
"id": "category",
"type": "multiple_choice",
"label": "Choose all categories that apply",
"required": false,
"field_metadata": {
"multi_select": true,
"values": [
{ "value": "travel", "label": "Travel" },
{ "value": "marketing", "label": "Marketing" }
]
}
}
]
}
The desired markup takes this shape:
<form>
<label class="field">
<input type="text" name="first-name" id="first-name" placeholder=" " required>
<span class="label">First name</span>
<em class="validation" hidden>First name is required.</em>
</label>
<label class="field checkbox-group">
<fieldset>
<div class="choice">
<input type="checkbox" value="travel" id="category-travel" name="category">
<label for="category-travel">Travel</label>
</div>
<div class="choice">
<input type="checkbox" value="marketing" id="category-marketing" name="category">
<label for="category-marketing">Marketing</label>
</div>
</fieldset>
<span class="label">Choose all categories that apply</span>
</label>
</form>
The empty placeholder=" " is deliberate: while the field is empty it matches input:placeholder-shown, giving CSS a hook without JavaScript and without visible placeholder text.
The plan: fetch the definitions and content from the API, initialize a DOMDocument, iterate over the fields building each one, and echo the output.
<?php
function renderForm ($endpoint) {
// Get the data from the API and convert it to a PHP object
$formResult = file_get_contents($endpoint);
$formContent = json_decode($formResult);
$formFields = $formContent->fields;
// Start building the DOM
$dom = new DOMDocument();
$form = $dom->createElement('form');
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// TODO: Do something with the field data
}
// Get the HTML output
$dom->appendChild($form);
$htmlString = $dom->saveHTML();
echo $htmlString;
}
Each field starts with a container <label> and a labelling <span> shared by all types. Because PHP does not scope variables inside loops, $label is reset on each pass; the label element is built only if the field has one, and appended to the container at the end. Classes go through setAttribute — unlike the Web API there is no special handling for class lists, they are just another attribute. Complex class logic can be assembled in an array and imploded.
<?php
// ...
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// Build the container `<label>`
$element = $dom->createElement('label');
$element->setAttribute('class', 'field');
// Reset input values
$label = null;
// Add a `<span>` for the label if it is set
if ($field->label) {
$label = $dom->createElement('span', $field->label);
$label->setAttribute('class', 'label');
}
// Add the label to the `<label>`
if ($label) $element->appendChild($label);
}
Single inputs, textareas, checkboxes, hidden fields
Since the API returns a known set of field types, a switch over the type is enough:
<?php
// ...
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// Build the container `<label>`
$element = $dom->createElement('label');
$element->setAttribute('class', 'field');
// Reset input values
$input = null;
$label = null;
// Add a `<span>` for the label if it is set
// ...
// Build the input element
switch ($field->type) {
case 'text':
case 'email':
case 'telephone':
$input = $dom->createElement('input');
$input->setAttribute('placeholder', ' ');
if ($field->type === 'email') $input->setAttribute('type', 'email');
if ($field->type === 'telephone') $input->setAttribute('type', 'tel');
break;
}
}
Text areas, single checkboxes and hidden fields are handled alongside:
<?php
// ...
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// Build the container `<label>`
$element = $dom->createElement('label');
$element->setAttribute('class', 'field');
// Reset input values
$input = null;
$label = null;
// Add a `<span>` for the label if it is set
// ...
// Build the input element
switch ($field->type) {
//...
case 'text_area':
$input = $dom->createElement('textarea');
$input->setAttribute('placeholder', ' ');
if ($rows = $field->field_metadata->rows) $input->setAttribute('rows', $rows);
break;
case 'checkbox':
$element->setAttribute('class', 'field single-checkbox');
$input = $dom->createElement('input');
$input->setAttribute('type', 'checkbox');
if ($field->field_metadata->initially_checked === true) $input->setAttribute('checked', 'checked');
break;
case 'hidden':
$input = $dom->createElement('input');
$input->setAttribute('type', 'hidden');
$input->setAttribute('value', $field->field_metadata->value);
$element->setAttribute('hidden', 'hidden');
$element->setAttribute('style', 'display: none;');
$label->textContent = '';
break;
}
}
The checkbox and hidden branches do something a string-based approach cannot easily do: they modify the container <label>, changing its class so a single checkbox aligns horizontally with its label and a hidden input's container disappears entirely. With concatenation, that would force type checks and metadata logic to the top of the block — or an earlier switch with common code copy-pasted into every branch. Here, nothing is final until saveHTML() runs, and everything stays structured.
Selects and grouped choices
For <select>, the outer element is created first, then an array of <option> elements is appended inside it.
<?php
// ...
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// Build the container `<label>`
$element = $dom->createElement('label');
$element->setAttribute('class', 'field');
// Reset input values
$input = null;
$label = null;
// Add a `<span>` for the label if it is set
// ...
// Build the input element
switch ($field->type) {
//...
case 'select':
$element->setAttribute('class', 'field select');
$input = $dom->createElement('select');
$input->setAttribute('required', 'required');
if ($field->field_metadata->multi_select === true)
$input->setAttribute('multiple', 'multiple');
$options = [];
// Track whether there's a pre-selected option
$optionSelected = false;
foreach ($field->field_metadata->values as $value) {
$option = $dom->createElement('option', htmlspecialchars($value->label));
// Bail if there's no value
if (!$value->value) continue;
// Set pre-selected option
if ($value->selected === true) {
$option->setAttribute('selected', 'selected');
$optionSelected = true;
}
$option->setAttribute('value', $value->value);
$options[] = $option;
}
// If there is no pre-selected option, build an empty placeholder option
if ($optionSelected === false) {
$emptyOption = $dom->createElement('option');
// Set option to hidden, disabled, and selected
foreach (['hidden', 'disabled', 'selected'] as $attribute)
$emptyOption->setAttribute($attribute, $attribute);
$input->appendChild($emptyOption);
}
// Add options from array to `<select>`
foreach ($options as $option) {
$input->appendChild($option);
}
break;
}
}
There is <select>-specific trickery: when no option is pre-selected, an empty placeholder option is added that is selected but cannot be chosen by the user. Appending it before the other options keeps it first in the markup, which lets the <label class="label"> act as a CSS-driven placeholder.
<?php
// ...
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// Build the container `<label>`
$element = $dom->createElement('label');
$element->setAttribute('class', 'field');
// Reset input values
$input = null;
$label = null;
// Add a `<span>` for the label if it is set
// ...
// Build the input element
switch ($field->type) {
// ...
case 'multiple_choice':
$choiceType = $field->field_metadata->multi_select === true ? 'checkbox' : 'radio';
$element->setAttribute('class', "field {$choiceType}-group");
$input = $dom->createElement('fieldset');
// Build a choice `<input>` for each option in the fieldset
foreach ($field->field_metadata->values as $choiceValue) {
$choiceField = $dom->createElement('div');
$choiceField->setAttribute('class', 'choice');
// Set a unique ID using the field ID + the choice ID
$choiceID = "{$field->id}-{$choiceValue->value}";
// Build the `<input>` element
$choice = $dom->createElement('input');
$choice->setAttribute('type', $choiceType);
$choice->setAttribute('value', $choiceValue->value);
$choice->setAttribute('id', $choiceID);
$choice->setAttribute('name', $field->id);
$choiceField->appendChild($choice);
// Build the `<label>` element
$choiceLabel = $dom->createElement('label', $choiceValue->label);
$choiceLabel->setAttribute('for', $choiceID);
$choiceField->appendChild($choiceLabel);
$input->appendChild($choiceField);
}
break;
}
}
Radio button and checkbox groups follow the same pattern: decide whether the set holds radios or checkboxes, set the container class accordingly, build the <fieldset>, then loop over the choices producing a <div> with an <input> and a <label> for each. Regular PHP string interpolation supplies the container class and a unique ID per choice.
Instruction fragments and inline validation
Forms often contain instruction fields — markup rather than inputs, printed between other fields. These need createDocumentFragment(), which accepts arbitrary HTML without DOM structuring:
<?php
// ...
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// Build the container `<label>`
$element = $dom->createElement('label');
$element->setAttribute('class', 'field');
// Reset input values
$input = null;
$label = null;
// Add a `<span>` for the label if it is set
// ...
// Build the input element
switch ($field->type) {
//...
case 'instruction':
$element->setAttribute('class', 'field text');
$fragment = $dom->createDocumentFragment();
$fragment->appendXML($field->text);
$input = $dom->createElement('p');
$input->appendChild($fragment);
break;
}
}
The variable holding a static <p> is called $input on purpose: every iteration consults a single variable name so the loop can end with $element->appendChild($input) regardless of field type.
Validation messages fit the same loop. The API supplies an individual message per required field, so errors can appear inline next to the relevant field instead of a generic notice at the bottom. No changes to the type logic are needed — just conditionally build one more element:
<?php
// ...
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// build the container `<label>`
$element = $dom->createElement('label');
$element->setAttribute('class', 'field');
// Reset input values
$input = null;
$label = null;
$validation = null;
// Add a `<span>` for the label if it is set
// ...
// Add a `<em>` for the validation message if it is set
if (isset($field->validation_message)) {
$validation = $dom->createElement('em');
$fragment = $dom->createDocumentFragment();
$fragment->appendXML($field->validation_message);
$validation->appendChild($fragment);
$validation->setAttribute('class', 'validation-message');
$validation->setAttribute('hidden', 'hidden'); // Initially hidden, and will be unhidden with Javascript if there's an error on the field
}
// Build the input element
switch ($field->type) {
// ...
}
}
Assembling the tree
After all field elements exist, $input, $label and $validation are attached to the tree, common attributes such as required are applied, and the submit button — supplied separately by the API — is added:
<?php
function renderForm ($endpoint) {
// Get the data from the API and convert it to a PHP object
// ...
// Start building the DOM
$dom = new DOMDocument();
$form = $dom->createElement('form');
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// Build the container `<label>`
$element = $dom->createElement('label');
$element->setAttribute('class', 'field');
// Reset input values
$input = null;
$label = null;
$validation = null;
// Add a `<span>` for the label if it is set
// ...
// Add a `<em>` for the validation message if it is set
// ...
// Build the input element
switch ($field->type) {
// ...
}
// Add the input element
if ($input) {
$input->setAttribute('id', $field->id);
if ($field->required)
$input->setAttribute('required', 'required');
if (isset($field->max_length))
$input->setAttribute('maxlength', $field->max_length);
$element->appendChild($input);
if ($label)
$element->appendChild($label);
if ($validation)
$element->appendChild($validation);
$form->appendChild($element);
}
}
// Build the submit button
$submitButtonLabel = $formContent->submit_button_label;
$submitButtonField = $dom->createElement('div');
$submitButtonField->setAttribute('class', 'field submit');
$submitButton = $dom->createElement('button', $submitButtonLabel);
$submitButtonField->appendChild($submitButton);
$form->appendChild($submitButtonField);
// Get the HTML output
$dom->appendChild($form);
$htmlString = $dom->saveHTML();
echo $htmlString;
}
The $input truthiness check matters: it is reset to null at the top of each iteration and only built for types the switch recognizes, so unrecognized elements never leak into the output.
Extending to rows and columns
Form builders commonly let authors define rows and columns — a row holding first-name and last-name fields at 50% each. The example API includes grid data for this:
{
"submit_button_label": "Submit now!",
"fields": [
{
"id": "first-name",
"type": "text",
"label": "First name",
"required": true,
"validation_message": "First name is required.",
"max_length": 30,
"row": 1,
"column": 1
},
{
"id": "category",
"type": "multiple_choice",
"label": "Choose all categories that apply",
"required": false,
"field_metadata": {
"multi_select": true,
"values": [
{ "value": "travel", "label": "Travel" },
{ "value": "marketing", "label": "Marketing" }
]
},
"row": 2,
"column": 1
}
]
}
The assumption is that a data-column attribute is sufficient for width styling, while each row must be its own element (no CSS grid). The logic is simple: track the latest row seen, and whenever the current row number increases, start a new row element and append to that instead of the previous one. In string-building, this means inserting markers like '</div><div class="row">' — reversed HTML that is hard to read, and a single typo produces a pile of auto-closed nested <div>s.
With the tree, add row tracking before the loop and an additional row container element, and append each field's $element to $rowElement rather than directly to $form:
<?php
function renderForm ($endpoint) {
// Get the data from the API and convert it to a PHP object
// ...
// Start building the DOM
$dom = new DOMDocument();
$form = $dom->createElement('form');
// init tracking of rows
$row = 0;
$rowElement = $dom->createElement('div');
$rowElement->setAttribute('class', 'field-row');
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// Build the container `<label>`
$element = $dom->createElement('label');
$element->setAttribute('class', 'field');
$element->setAttribute('data-row', $field->row);
$element->setAttribute('data-column', $field->column);
// Add the input element to the row
if ($input) {
// ...
$rowElement->appendChild($element);
$form->appendChild($rowElement);
}
}
// ...
}
Inside the loop, a new row element is created when the row number advances:
<?php
// ...
// Init tracking of rows
$row = 0;
$rowElement = $dom->createElement('div');
$rowElement->setAttribute('class', 'field-row');
// Iterate over the fields and build each one
foreach ($formFields as $field) {
// ...
// If we've reached a new row, create a new $rowElement
if ($field->row > $row) {
$row = $field->row;
$rowElement = $dom->createElement('div');
$rowElement->setAttribute('class', 'field-row');
}
// Build the input element
switch ($field->type) {
// ...
// Add the input element to the row
if ($input) {
// ...
$rowElement->appendChild($element);
// Automatically de-duped
$form->appendChild($rowElement);
}
}
}
Overwriting $rowElement with a fresh DOM element is enough, because PHP treats it as a new unique object. Each iteration simply appends whatever the current $rowElement is: the existing row gets the field if nothing changed, and a new element lands at the end of the form when the row advances.
When to reach for DOMDocument
Forms are a natural fit for object-oriented templating, and nested navigation menus would likely fare better than the WordPress string approach. In general, any markup driven by complex logic qualifies. Since DOMDocument writes any XML, the same tool can generate an RSS feed from post data.
DOMDocument also parses existing HTML and XML; elements can then be queried through the XPath API (DOMXPath), roughly analogous to document.querySelector or Node's cheerio. The learning curve is real, but it is a powerful way to process external content. For context on how far the format reaches: Office files with the x suffix (e.g. .xlsx) are XML, so Word documents can be parsed and rendered to HTML server-side.
Templating remains the core capability: producing the right markup for the right situation is what makes a good UX possible.



