Frage

I still can't really wrap my head around the built in DOMDocument class.

Why should I use that instead of just doing it similar to the following?

I would like to know the benefits.

$URI    = $_SERVER['REQUEST_URI'];
$navArr = Config::get('navigation');

$navigation = '<ul id="nav">' . "\n";
foreach($navArr as $name => $path) {
    $navigation .= '    <li' . ((in_array($URI, $path)) ? ' class="active"' : false) . '><a href="' . $path[1] . '">' . $name . '</a></li>' . "\n";
}
$navigation .= '</ul>' . "\n\n";

return $navigation;
War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top