New Create HTML documents using DOM API in PHP 8.4
New Create HTML documents using DOM API in PHP 8.4
Video Lesson: Create HTML documents using DOM API in PHP 8.4
Use the new DOM API to create elements in PHP to parse or manipulate complex HTML structures.
Published 1 week ago
Share with colleagues:
Lesson Content
PHP 8.4 introduces new DOM classes that make working with HTML significantly easier. The new API is more spec-compliant while maintaining backward compatibility.
This DOM API is perfect for programmatically parsing or manipulating complex HTML structures. You'll find it invaluable when building scrapers, transforming HTML from external sources, or ensuring well-formed output with proper escaping for security.
Let's create and work with HTML using the Dom\HTMLDocument
class:
$dom = Dom\HTMLDocument::createFromString(
<<<HTML
<header>
<h1>Welcome to my website</h1>
<nav class="primary">
<a href="/">Home</a>
<a href="/about" class="featured">About</a>
<a href="/contact">Contact</a>
</nav>
</header>
HTML,
LIBXML_NOERROR,
);
The createFromString()
static method lets you quickly parse HTML fragments. I'm using PHP's heredoc syntax here to make working with HTML cleaner. The second parameter takes libxml parsing options - we're using LIBXML_NOERROR
to suppress errors for malformed HTML.
Once you have a document, you can then use modern CSS selectors to find elements:
// Find the featured navigation link using CSS selectors
$featuredLink = $dom->querySelector("nav > a.featured");
The querySelector()
method returns the first element matching your selector, just like its related counterpart in JavaScript with the same name.
Working with element classes is also much more intuitive. The classList
property provides a clean way to check, add, remove, or toggle classes:
// Check if an element has a specific class
var_dump($featuredLink->classList->contains("featured")); // bool(true)
This eliminates the need for awkward string manipulation or regular expressions when working with HTML classes.