Manipulate HTML Using DOMDocument In PHP

DOM DOCUMENT PHP

27th July 2020

4 mins read

Share Article  Share On Twitter   Share On WhatsApp   Share On Telegram

Sometimes there might arise a situation to alter the stored HTML of the database to display on the fly to the user or you might want to play around with XML from PHP. This is where the **DOMDocument** of PHP comes to place.

NOTE: No need for any external libraries. It’s built-in hidden gem of PHP.

We will be covering the following topics

  1. What was the problem that forced me to use DOMDocument
  2. DOMDocument Basics
  3. Implementation To My Project

1) The Problem

Basically, I faced the problem when writing code for the existing blog to AMP version blog.

I had my articles code snippets, images, iframes, and other HTML elements stored inside the database. These HTML elements are not directly compatible with AMP HTML and have to be replaced, common tags that I had to replace are as follows

img -> amp-img

iframe -> amp-iframe

Not only elements even a few **attributes** of HTML elements were not supported.

I was earlier working on WYSIWYG editors and stumbled upon PHP’s hidden gem ie, DomDocument.


2) DomDocument Basics

DomDocument object is similar to that of your Javascript DOM. In case if you have earlier worked with Javascript DOM manipulation then it will be really simpler for you.

DOMDocument Initialization (DOMDocument())

You can start playing around with PHP DOMDocument by initializing it as follows

$dom = new \DOMDocument();

Loading HTML or XML Content (loadHtml / loadXml)

Now, we have to load the HTML or XML document we would like to playaround.

#html

Manipulate HTML Using DOMDocument In PHP
1.65 GEEK