herveguetin
9/9/2014 - 5:22 PM

Replace HTML tags using PHP DOM objects and Zend_Dom_Query

Replace HTML tags using PHP DOM objects and Zend_Dom_Query

<?php
  $replacedTags = array(
      'dt' => array( // <dt> tag is replaced by...
          'tag' => 'div', // ... <div> tag...
          'attributes' => array( // ... with these attributes
              'class' => 'some-class',
              'id' => 'some_id',
              'data-something' => 'some-value'
          )
      ),
      'dd' => array(
          'tag' => 'div',
          'attributes' => array(
              'class' => 'some-other-class',
              'id' => 'some_other_id',
              'data-something' => 'some-other-value'
          )
      )
  );

  // Create a new item that will contain our new DOM elements
  $newItem = new DOMDocument();

  // Create a Zend_Dom_Query object in order to find tags to replace
  $html = '<dt>Some DT</dt><dd><div>Some DD content</div></dd>'; // Your source HTML
  $html = utf8_decode($html);
  $domQuery = new Zend_Dom_Query($html);

  // Create DOM content for $newItem
  foreach ($replacedTags as $tag => $config) {

      // Find DOM elements matching the tag to replace
      $searchedDomElements = $domQuery->query($tag);

      foreach ($searchedDomElements as $searchedDomElement) {

          // Create a new DOM element in $newItem with new tag...
          $newDomElement = $newItem->createElement($config['tag']);

          // ... and set updated attributes on this new DOM element
          foreach($config['attributes'] as $attribute => $value) {
              $newDomElement->setAttribute($attribute, $value);
          }

          // Inject all child nodes from $searchedElement into the new DOM element
          $children = $searchedDomElement->childNodes;
          foreach($children as $child) {

              // Create a DOM element in $newItem that is a clone of $child and with all $child's nodes...
              $newDomElementChild = $newItem->importNode($child, true);

              // ... and append this DOM element to the new DOM element
              $newDomElement->appendChild($newDomElementChild);
          }

          // Once the new DOM element is ready, append it to the $newItem
          $newItem->appendChild($newDomElement);
      }
  }

  // Generate HTML out of complete $newItem
  $updatedHtml = $newItem->saveHTML();
  return utf8_encode($updatedHtml);