Skip to main content

Command Palette

Search for a command to run...

Outputting XHTML with PHP DOMDocument

Published
•1 min read•View as Markdown
G

Hello, I'm Gaurav Kumar PHP Framework Expert with 8+ Years of Experience

I am an experienced PHP framework expert with over 8 years of dedicated experience. Specializing in frameworks like Laravel, Symfony, CodeIgniter, and Zend. With a deep understanding of web development intricacies, I excel in developing custom web applications, e-commerce platforms, content management systems, and API integrations. I am well-versed in modern development practices, including OOP, MVC architecture, RESTful APIs, and version control systems.

If you are in need of any help on PHP frameworks, You can contact me. I will love to help you! 😊

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/>.

More from this blog

Gaurav Kumar PHP Framework Expert with 8+ Years of Experience

13 posts

Hello, I'm Gaurav Kumar PHP Framework Expert with 8+ Years of Experience.