Remove style tags from HTML using PHP’s DOMDocument class

Hi friends, in this tutorial I will show you how to remove style tags from HTML using PHP’s DOMDocument class. DOMDocument is a built-in class of PHP. It can parse HTML code, find matches and replace parts of the HTML code if any match found.

Also, you may be interested to read the following tutorials —

Remove style tags from HTML using PHP's DOMDocument class

Let’s proceed to the PHP code —

Here in this tutorial, I created a PHP function that will remove style tags from HTML elements.

Remove style tags from HTML using PHP’s DOMDocument class

	<?php
	function removeStyleTags($html="") {
		$doc = new DOMDocument();
		libxml_use_internal_errors(true);
		$doc->loadHTML($html);
		$doc->encoding = 'UTF-8';
		$path = new DOMXPath($doc);
		$nodes = $path->query("//*[@style]");
		foreach ($nodes as $node) {
			$node->removeAttribute('style');
		}
		$html_new = $doc->saveHTML();
		return $html_new;
	}
	?>

Detaild explanation :

We need to create an object of DOMDocument class by initiating it like below.

$doc = new DOMDocument();

In many cases it is advisable to use libxml_use_internal_errors(true); before $doc->loadHTML($html); By using this way warning will not be thrown and the page will be loaded anyway.

libxml_use_internal_errors(true);

To parses or loads HTML contained in the string we will use below funtion

$doc->loadHTML($html);

To retreive selected HTML data we will use

$path = new DOMXPath($doc);

Find and store any element with a style attribute

$nodes = $path->query("//*[@style]");

Next, we will loop through the nodes and remove the style tag —

foreach ($nodes as $node) {
    $node->removeAttribute('style');
}

At last, dumps the internal document into a string using HTML formatting —

$html = $doc->saveHTML();

Atlast, call the removeStyleTags($str) function as per your need like below –

<?php 
$str = '<p style="text-align: justify;"><span style="font-weight: bold;">Lorem ipsum</span> dolor sit amet, consectetur adipiscing elit, sed do <span style="color:#f90c61;">eiusmod</span> tempor incididunt ut labore et <span style="font-size: 20px;">dolore</span> magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut <span style="color:#f90c61;">aliquip ex ea</span> commodo consequat. <span style="font-weight: bold;">Duis aute irure</span> dolor in reprehenderit in voluptate <span style="color:#1909f5;">velit esse</span> cillum dolore eu fugiat nulla pariatur. <span style="font-size:20px; color:#05ef19;"">Excepteur</span> sint occaecat cupidatat non proident, sunt in culpa qui <span style="letter-spacing: 0.5em;">officia</span> deserunt mollit anim id est laborum.</p>';

echo removeStyleTags($str);
?>

Leave a Reply

Your email address will not be published. Required fields are marked *