/** * Class textSummary * Generates a text summary from a string, preserving any html markup and whole words or sentences (depending on options). */ class TextSummary { public $safeValue; public $sumamry; public $trimLength; public $ellipses; public $dom; public $total; function __construct($safe_value, $trim_length, $ellipsis = NULL) { $this->safeValue = $safe_value; $this->summary = ''; $this->trimLength = $trim_length; $this->total = 0; $this->ellipses = $ellipsis; $this->dom = Html::load($safe_value); } /** * A starting point for the recursion. */ function getSummary() { $this->traverseChildren($this->dom); return $this->summary; } function traverseChildren ($domElement) { // Maybe check for the instanceof DOMElement first and get the tag name? if ($domElement instanceof DOMElement) { // Recurse!!! //if($domElement->hasChildNodes()) foreach ($domElement->childNodes as $childNode) { $hasMoreChildNodes = $childNode->hasChildNodes(); if ($hasMoreChildNodes) { $newChild = $this->traverseCildren($childNode); $domElement->replaceChild($newChild, $childNode); } } } else if ($domElement instanceof DOMText) { // Count the characters // Compare to the total if($this->total + strlen($domElement->textContent) <= $this->trimLength ) { // TODO: This is wrong, but ok to get started. return $domElement->textContent; } // If it exceeds the total, break up by sentence and add that to the current summary, // else concatenate the complete DOMText to the summary, plus surrounding tags? } else if($domElement instanceof DOMDocument){ // This will always be the first call, so we get the body element and traverse that. $body = $domElement->getElementsByTagName('body'); foreach ($body as $domNode) { $this->traverseCildren($domNode); //TODO: left off with an error here, I don't know why. } } } }