Project

General

Profile

Feature #16836 ยป cropHTML.txt

Administrator Admin, 2007-01-06 20:24

 
//parse given html
$doc = domxml_xmltree('<body>' . $content . '</body>');
$body = $doc->get_elements_by_tagname('body');
$length = 0;
$content = cropHTML($body[0], $length, $cropHtml);


echo $content;


function cropHTML(&$node, &$length, $maxLength = 200, $replaceString = '...') {
$st = "";
if ($length >= $maxLength)
return $st;
foreach ($node->child_nodes() as $cnode){
if ($cnode->node_type() == XML_TEXT_NODE) {
$text = $cnode->node_value();
if (strlen($text) + $length < $maxLength) {
$st .= $text;
$length += strlen($text);
} else if ($length < $maxLength) {
$st .= substr($text, 0, $maxLength - $length) . $replaceString;
$length = $maxLength+1;
return $st;
}
} else {
if ($cnode->node_type() == XML_ELEMENT_NODE) {
$st .= "<" . $cnode->node_name();
if ($attribnodes = $cnode->attributes()) {
$st .= " ";
foreach ($attribnodes as $anode) {
$st .= $anode->node_name() . "='" .$anode->node_value() . "'";
}
}
$nodeText = cropHTML($cnode, $length, $maxLength, $replaceString);
if (empty ($nodeText) && !$attribnodes)
$st .= " />"; // unary
else
$st .= ">" . $nodeText . "</" . $cnode->node_name() . ">";
}
}
if($length >= $maxLength) break;
}
return $st;
}
    (1-1/1)