Using DOMDocument to Modify HTML with PHP

By  on  
One of the first things you learn when wanting to implement a service worker on a website is that the site requires SSL (an https address).  Ever since I saw the blinding speed service workers can provide a website, I've been obsessed with readying my site for SSL.  Enforcing SSL with .htaccess was easy -- the hard part is updating asset links in blog content.  You start out by feeling as though regular expressions will be the quick cure but anyone that has experience with regular expression knows that working with URLs is a nightmare and regex is probably the wrong decision. The right decision is DOMDocument, a native PHP object which allows you to work with HTML in a logical, pleasant fashion.  You start by loading the HTML into a DOMDocument instance and then using its predictable functions to make things happen.
// Formats post content for SSL
function format_post_content($content = '') {
  $document = new DOMDocument();
  // Ensure UTF-8 is respected by using 'mb_convert_encoding'
  $document->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
  
  $tags = $document->getElementsByTagName('img');
  foreach ($tags as $tag) {
    $tag->setAttribute('src', 
      str_replace('http://davidwalsh.name', 
                  'https://davidwalsh.name', 
                  $tag->getAttribute('src')
      )
    );
  }
  return $document->saveHTML();
}
In my example above, I find all img elements and replace their protocol with https://.  I will end up doing the same with iframe src, a href, and a few other rarely used tags.  When my modifications are done, I call saveHTML to get the new string. Don't fall into the trap of trying to use regular expressions with HTML -- you're in for a future of failure.  DOMDocument is lightweight and will make your code infinitely more maintainable.

Recent Features

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • By
    5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

Incredible Demos

  • By
    MooTools OpenLinks Class – Updated

    A long time back I coded a MooTools class called OpenLinks. The class is quite useful but the code...sucks. I've gotten much better with MooTools over the past years so I thought I'd go back and update the class to be better, faster...

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

Discussion

  1. Manny Fleurmond

    So do you know if there is a performance hit with creating an element using this vs creating a string of html?

  2. zakius

    The right decision is skipping domain entirely if it isn’t hosted on some subdomain (/path/to/asset), and skipping protocol if it is ((//example.com/path/to/asset)

  3. David, rather than str_replace all your (internal) http:// strings with https:// you should replace them with // – that way your links become protocol-agnostic — a more future-proof solution.

  4. Why don’t you use the search-replace function in WP-CLI?

  5. Silvestre

    Why not remove the protocol completely?

    //davidwalsh.name/ would default to whatever protocol is used in the address bar.

  6. I agree that // would be better but some RSS feed readers use http, others https. I’m asserting complete control.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!