Sample Code

Table of Contents

Import from file

				
					// read the HTML file into a local variable
$html = file_get_contents( ‘example.html’ );

// create an instance of the HTML Parser class object
$dom = new \HTML\Document;

// import the HTML and create the DOM
$IsSuccessful = $dom->load( $html );

				
			

Export

				
					// convert the DOM in the HTML Parser object to an HTML string
$html = $dom->export();
				
			

Modify – add a new attribute, or replace an existing attribute value

				
					// create an instance of the HTML Parser class object
$dom = new \HTML\Document;

// import the HTML and create the DOM
// note: you must have already loaded the HTML in the PHP variable named $html
$IsSuccessful = $dom->load( $html );

// get a reference to the node with the ID
$element = $dom->findById( ‘blah’ );

// add a new attribute to the element, or modify an existing attribute
$element->setAttribute( ‘a’, ‘b’ );

// convert the DOM in the HTML Parser object to an HTML string
$html = $dom->export();
				
			

Modify – read-modify-write an existing attribute value

				
					// create an instance of the HTML Parser class object
$dom = new \HTML\Document;

// import the HTML and create the DOM
// note: you must have already loaded the HTML in the PHP variable named $html
$IsSuccessful = $dom->load( $html );

// get a reference to the node with the ID
$element = $dom->findById( ‘blah’ );

// get the current value of the attribute
$value = $element->getAttribute( ‘class’ );

// modify the local copy of the attribute value
$value .= ‘ blah’;

// update the attribute value in the DOM
$element->setAttribute( ‘a’, ‘b’ );

// convert the DOM in the HTML Parser object to an HTML string
$html = $dom->export();
				
			
Scroll to Top