Outputting XHTML with PHP DOMDocument
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:
- 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">');
- 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);
- 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/>
.
ย