Here's the same example using DOMDocument:
$doc = new DOMDocument;
$list = $doc->appendChild($doc->createElement('ul'));
$list->setAttribute('id', 'nav');
foreach ($navArr as $name => $path) {
$listItem = $list->appendChild($doc->createElement('li'));
if (in_array($URI, $path)) {
$listItem->setAttribute('class', 'active');
}
$link = $listItem->appendChild($doc->createElement('a'));
$link->setAttribute('href', $path[1]);
$link->appendChild($doc->createTextNode($name));
}
return $doc->saveHTML();
It's more verbose, but not too much, and possibly clearer what's happening at each step.
One benefit is character escaping: createTextNode
and setAttribute
ensure that the special HTML characters (quotes, ampersands and angle brackets) are escaped properly.
In the end, though, for a larger application, you'd probably want to use an actual templating language like Twig for generating HTML, as the templates are more readable and extensible.