Outputting XHTML with PHP DOMDocument

ยท

1 min read

When using PHP's DOMDocument to output XHTML, it's important to note that XHTML requires explicit closing tags for empty elements. The self-closing notation, commonly used in HTML, is not valid in XHTML. To output XHTML-compliant markup with PHP's DOMDocument, you can follow these guidelines:

  1. Create an instance of DOMDocument and set the document type to XHTML:
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->xmlStandalone = true;
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
  1. Create and append elements to the document:
$html = $dom->createElement('html');
$dom->appendChild($html);

$body = $dom->createElement('body');
$html->appendChild($body);

$div = $dom->createElement('div');
$body->appendChild($div);

$span = $dom->createElement('span', 'This is an example');
$div->appendChild($span);
  1. Output the XHTML markup:
echo $dom->saveXML();

The resulting output will be valid XHTML with explicit closing tags for empty elements, such as <div></div> instead of <div/>.

ย