HTML Excerpt with PHP

Filed in PHP February 3rd, 2013 by Morgan Ney

Most blog owners would like to be able to show excerpts or previews of their articles as HTML. This allows the excerpt to be styled similarly to the post's landing page, providing a seamless transition for the reader from excerpt to full article.

Here is an example of how to create an HTML excerpt using PHP's DOMDocument class, where $html represents the entire article, and $num_chars the lower bound to the number of characters in the excerpt.

// requires PHP >= 5.3.6 to support saveHTML([$node])
function getPostPreview($html, $num_chars) {
  if(strlen($html) <= $num_chars) $preview = $html;
  else {
    $preview = '';
    $dom = $DOMDocument::loadHTML($html); // creates DOCTYPE, <html>, and <body>
    $dom->removeChild($dom->firstChild); // DOCTYPE
    /*
     * If your post is wrapped by a parent element with an id:
     * $node = $dom->getElementById('id')->firstChild
     * Otherwise skip <html> and <body> and grab the first element of your post
     */
    $node = $dom->firstChild->firstChild->firstChild;
    while(strlen($preview) <  $num_chars) {
      $preview .= $dom->saveHTML($node);
      $node = $node->nextSibling;
    }
  }
  return $preview;
}

Note that this function will not break your HTML and returns a valid HTML preview of your blog's articles. I use it for excerpts on this blog. If you find it useful please bump up my answer on stackoverflow.

AWS Product Advertising API Requires a Signed Request

Filed in PHP August 21st, 2010 by Morgan Ney

As of August 15th 2009, the AWS Product Advertising API requires a signed request. PHP provides useful library functions for creating the required RFC 2104 compliant HMAC signature. If your calls to the AWS API are being rejected, it is time to start authenticating your requests with a valid signature.

Amazon Web Services with PHP and SimpleXML

Filed in PHP December 30th, 2009 by Morgan Ney

Amazon's web services use REST and provide an easy introduction to the current vastness of web service API's out there. Additionally, PHP and it's SimpleXML extension comprise an effective toolkit for requesting and later parsing XML respones from AWS.

Preliminary SEO Checklist and Tips

Filed in SEO June 1st, 2009 by Morgan Ney

One of the most overlooked opportunities for SEO is the pre-development phase. Too often SEO is considered only after a website is finished, and many chances for SEO have been lost. This SEO checklist will offer tips on some of the most important preliminary SEO strategies.

Object Oriented Programming and Late Binding with PHP

Filed in PHP February 19th, 2009 by Morgan Ney

PHP 5 offers improved support for Object-oriented programming (OOP). In particular, it now supports late binding (dynamic binding) to allow for richer forms of polymorphism through inheritance.