Building a Form in PHP Using DOMDocument

Templating makes the web go round. The synthesis of data and structure into content. It’s our coolest superpower as developers — grab some data, then make it work for us, in whatever presentation we need. An array of objects can become a table, a list of cards, a chart, or whatever we think is most useful to the user. Whether the data is our own blog posts in Markdown files, or on-the-minute global exchange rates, the markup and resulting UX are up to us as front-end developers.
PHP is an amazing language for templating, providing many ways to merge data with markup. Let’s get into an example of using data to build out an HTML form in this post.

Want to get your hands dirty right away? Jump to the implementation.
In PHP, we can inline variables into string literals that use double quotes, so if we have a variable $name=”world”, we can write echo “Hello, {$name}”, and it prints the expected Hello, world. For more complex templating, we can always concatenate strings, like: echo “Hello, ” . $name . “.”.
For the old-schoolers, there’s printf(“Hello, %s”, $name). For multiline strings, you can use Heredoc (the one that starts like <<Hello,

All of these options are great, but things can get messy when a lot of inline logic is required. If we need to build compound HTML strings, say a form or navigation, the complexity is potentially infinite, since HTML elements can nest inside each other.
What we’re trying to avoid
Before we go ahead and do the thing we want to do, it’s worth taking a minute to consider what we don’t want to do. Consider the following abridged passage from the scripture of WordPress Core, class-walker-nav-menu.php, verses 170-270:
// …
$item_output = $args->before;
$item_output .= ‘‘;
$item_output .= $args->link_before . $title . $args->link_after;
$item_output .= ‘‘;
$item_output .= $args->after;
// …
$output .= apply_filters( ‘walker_nav_menu_start_el’, $item_output, $item, $depth, $args );
// …
$output .= “

In order to build out a navigation

One comment

  1. Hi there, this ᴡeekend is fastіdious in supрⲟrt of me, as this moment i am reading this
    wonderful educational post here at my home.

Leave a Reply