DOM DOCUMENT PHP
27th July 2020
4 mins read
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
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.
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()
)You can start playing around with PHP DOMDocument by initializing it as follows
$dom = new \DOMDocument();
loadHtml
/ loadXml
)Now, we have to load the HTML or XML document we would like to playaround.
#html