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.