This page looks best with JavaScript enabled

DOMDocument Class in PHP

 ·  ☕ 1 min read  ·  🤖 Arjit Sharma

Represents an entire HTML or XML document. It serves as the root of the document tree. Helps in parsing and creating xml,html

Loading HTML

file_get_contents(URL) : Converts html content in URL to String.
loadHTML(file_get_contents(URL)) : Loading HTML string with DomDocument object.

1
2
3
4
doc=new DomDocument();
//convert html of a URL to string using file_get_contents
//loading HTML string
$doc->loadHTML(file_get_contents(URL));

Functions to get HTML contents

1
2
3
4
5
6
7
$doc->getElementsById("idName");

//Gets all anchor tags inside Document
$doc->getElementsByTagName("a");

//Gets all src attributes in img in whole doc
$doc->getElementsByTagName("img")->getAttribute('src');

Creating and Adding elements in HTML Doc

1
2
3
4
$div = doc->createElement('div');//create a div
$div_clone = $div->cloneNode();//Cloning div to div_clone
$doc->appendChild($div);//Appending div to Document
$doc->saveHTML();//Saves document

Traversing all entries of a element

item() : Gets node at certain index within DOMNodeList object.
nodeValue : Gets value at that node.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php

$doc = new DOMDocument;
$doc->load('arjit.html');

$items = $doc->getElementsByTagName('a');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "\n";
}
/*
foreach ($items as $item) {
    echo $item->nodeValue . "\n";
}
*/

?>
Share on

Arjit Sharma
WRITTEN BY
Arjit Sharma
Yo, I am a CS enthusiast or am I ? Just kidding.


What's on this Page