Wednesday, March 16, 2016

Manipulate Joomla Content With DOMDocument PHP

The DOMDocument Php class is great for reading and manipulating elements on a page. It's similar to jQuery for PHP. The sample code below loads the body from Joomla, throws it into a DOMDocument, and then updates the page with whatever changes you make to the DOMDocument.

//I used this code in a system plugin
public function onAfterRender(){
    $app = JFactory::getApplication();
    if ($app->isSite()){

   $pageBody = $app->getBody();

   $domDoc = new DOMDocument();

  //Your code here


You could then, for example, iterate through all the classes in the document and add a responsive class to them:

$images = $domDoc->getElementsByTagName('img');
 foreach ($images as $img) {
  $imgclass = $img->getAttribute('class');
  $img->setAttribute('class', $imgclass . ' responsive-img');


Post a Comment