Truncate SimplePie Content with PHP

This article is a follow-up to an earlier blog post about using SimplePie to display an RSS feed on your website.

Sometimes it can be useful to ensure that a piece of content stays on a single line (e.g. a title), or make sure that some text stays to less than 255 characters (e.g. a description) and gets truncated after that point.

My previous blog article showed how to do this with PHP, and I will give a brief recap below. However, the focus of this blog post is to improve truncation of content even further.

Old Truncation Technique

The following PHP string truncates or shortens the title to 45 characters and then echo’s the list of titles parsed from an RSS feed and displays it on the page with ellipses (…) appended to the end of the title: < ?php echo substr($item->get_title(), 0, 42) . '...'; ?>

For example: Here Is a Title That Is 42 Characters long… You can see that the title itself is 42 characters long so it hasn’t been truncated, but the PHP has appended ellipses (…) to the end of the title. Doing this is quite unnecessary unless the title is over 42 characters.

Improved Truncation Technique

The way to deal with this more effectively is to determine the length of the string and then only append the ellipses (…) if the length of the string exceeds the parameters we have set.

This can be done as follows:

get_description(), 0, 45);
  $str = $item->get_description();
  if (strlen($str) > 45) echo '...';
?>

To explain the above code line by line, echo substr($item->get_title(), 0, 45);, this line echo’s or outputs the parsed feed title using SimplePie. The substr function returns the portion of string specified by the start and length parameters. In the above case, 0 represents the first character, and 45 represents the 45th character (spaces are included as characters).

If the title is 45 characters or less, the above code works fine and doesn’t append the ellipses (…), which is ideal. However, what if the title is 60 characters in length?

The second line of the above code, $str = $item->get_description(); converts the whole title into a string called $str.

The third line of code uses the strlen function, which returns the length of the given string (which we have called $str). By using an if statement in the final line of code if (strlen($str) > 45) echo '...';, we are saying, if the length of the string is greater than 45 characters show the ellipses (…) otherwise ignore the if statement and don’t show the ellipses (…).

It’s a very simple tweak that can be applied to outputting SimplePie or any other PHP, and it can help to retain a better looking page by avoiding text wrapping.