PHP DOMDocument Class Tutorial 🎯

beginner
11 min

PHP DOMDocument Class Tutorial 🎯

Welcome to our comprehensive guide on the PHP DOMDocument Class! This tutorial is designed to help you understand and master this powerful tool, ideal for beginners and intermediates alike. Let's dive in!

Understanding DOMDocument Class πŸ“

The DOMDocument Class in PHP is a part of the DOM extension, providing an interface for parsing and manipulating XML and HTML documents. It's a vital tool when dealing with web scraping, content management systems, and more.

Creating a DOMDocument Object πŸ’‘

To create a DOMDocument object, you can use the DOMDocument constructor, like so:

php
$dom = new DOMDocument();

Loading an XML or HTML Document πŸ’‘

You can load an XML or HTML document into a DOMDocument object using the load() method. Here's an example:

php
$dom = new DOMDocument(); $dom->loadHTMLFile('example.html');

Exploring the Document Tree πŸ’‘

Once you've loaded a document, you can explore its structure, also known as the document tree, using various methods like getElementsByTagName(), getElementsByTagNameNS(), and more.

Manipulating the Document Tree πŸ’‘

You can manipulate the document tree using various methods like createElement(), createTextNode(), appendChild(), replaceChild(), and so on.

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

How do you create a DOMDocument object in PHP?

Real-World Example πŸ’‘

Let's say you want to extract all the links from an HTML document. Here's how you can do it:

php
$dom = new DOMDocument(); $dom->loadHTMLFile('example.html'); $links = $dom->getElementsByTagName('a'); foreach ($links as $link) { $href = $link->getAttribute('href'); echo $href; }

Advanced Example πŸ’‘

In this example, we'll create an HTML document, add some elements, and save it to a file:

php
$dom = new DOMDocument('1.0', 'UTF-8'); $title = $dom->createElement('title'); $titleText = $dom->createTextNode('My New Website'); $title->appendChild($titleText); $body = $dom->createElement('body'); $header = $dom->createElement('header'); $headerText = $dom->createTextNode('Welcome to my new website!'); $header->appendChild($headerText); $body->appendChild($header); $dom->appendChild($title); $dom->appendChild($body); $dom->saveHTMLFile('new_website.html');

That's it for this tutorial! Remember to practice regularly to master the DOMDocument Class in PHP. Happy coding! πŸŽ‰