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.

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

   $pageBody = $app->getBody();

   $domDoc = new DOMDocument();
  $domDoc->loadHTML($pageBody);

  //Your code here

  $app->setBody($domDoc->saveHTML());
 }
}
?>

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

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

0 comments:

Post a Comment