Kcko
10/22/2018 - 9:27 AM

PHPDOM - examples

  1. responsive image wrapper - replace child
  2. remove internal style from html
  // Create a DOMDocument
  $dom = new DOMDocument();
	
  // Load html including utf8, like Hebrew
  $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
	
  // Create the div wrapper
  $div = $dom->createElement('div');
  $div->setAttribute('class', 'responsive-img');
	
  // Get all the images
  $images = $dom->getElementsByTagName('img');
 
  // Loop the images
  foreach ($images as $image) 
  {
    //Clone our created div
    $new_div_clone = $div->cloneNode();
		
    //Replace image with wrapper div
    $image->parentNode->replaceChild($new_div_clone,$image);
		
    //Append image to wrapper div
    $new_div_clone->appendChild($image);
  }
	
  // Save the HTML
  $html = $dom->saveHTML();
	
  return $html;
 $dom = new DOMDocument;                
	
  $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
	
  $xpath = new DOMXPath($dom); 
	
  // Find any element with the style attribute
  $nodes = $xpath->query('//*[@style]');  
	
  // Loop the elements
  foreach ($nodes as $node)               
  {             
    // Remove style attribute
    $node->removeAttribute('style');
  }
  $html = $dom->saveHTML(); 
	
  return $html;