PHP's DomDocument Cheatsheet

Your one stop quick loading page for a full PHP DomDocument cheatsheet and lots of working examples.

This is a work in progress. Lets call it BETA.


Basic DOM Document example - Get element with an ID

<?php
// get your HTML
$html file_get_contents("http://example.com/");

// Create a new dom object
$dom = new domDocument;

// load HTML
$dom->loadHTML($html);

// now lets get a tag based on its ID
$contents_div $dom->getElementById("contents");

var_dump($contents_div); // will be false if no #contents element in $html

if ($contents_div) {
    echo 
$dom->saveHTML($contents_div); // echo its contents
  
}

?>

Get all elements based on the type of tag

This lets you get all

<img>
tags, or maybe extract all
<a>
tags etc..


<?
$images 
$dom->getElementsByTagName("img");
$i 0;
$num $images->length;
if (
$num>0) {
  while(
$img $images->item($i++)) {
    echo 
$dom->saveHTML($table);
  }
}
?>
  
HomeContact/About usPHP's DomDocument CheatsheetTerms and Conditions • We do not set any cookies on our website. Please refer to our privacy policy for more details about our cookies.