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!
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.
To create a DOMDocument object, you can use the DOMDocument constructor, like so:
$dom = new DOMDocument();You can load an XML or HTML document into a DOMDocument object using the load() method. Here's an example:
$dom = new DOMDocument();
$dom->loadHTMLFile('example.html');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.
You can manipulate the document tree using various methods like createElement(), createTextNode(), appendChild(), replaceChild(), and so on.
How do you create a DOMDocument object in PHP?
Let's say you want to extract all the links from an HTML document. Here's how you can do it:
$dom = new DOMDocument();
$dom->loadHTMLFile('example.html');
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
$href = $link->getAttribute('href');
echo $href;
}In this example, we'll create an HTML document, add some elements, and save it to a file:
$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! π