PHP Tidbits

24 Oct 2006

I'm developing a new web site for from the ground up, focusing on a clean, accessible design. As a result, I've been noticing all of the things I dislike about blogs, mine included. Navigation, commenting, and community are some aspects that I especially hope to improve.

I must admit, though, that instead of diving right in, I've been goofing off. Just for fun, I'd like to share a couple of quick PHP tidbits with you that I wrote instead of starting on the real project at hand. :-)

The first is an example that really shows off how useful a simple REST API can be in combination with SimpleXML. I've been using FeedBurner for a while for my feed, and it's cool to see how many people are subscribed. As part of the new design, I'd like to be able to grab that number without having to use their image. Enter the FeedBurner Awareness API. With two lines of PHP, I'm good to go:

  2. $info = simplexml_load_file('');
  3. $subscribers = $info->feed->entry['circulation'];

Formatting can be difficult when you have really long URLs, and one of the best solutions I've seen is to shorten URLs to just the first x characters and the last y characters. Something like this:

  2. function shorten_url($url, $separator = '...', $first_chunk_length = 35, $last_chunk_length = 15)
  3. {
  4.     $url_length = strlen($url);
  5.     $max_length = $first_chunk_length + strlen($separator) + $last_chunk_length;
  7.     if ($url_length > $max_length) {
  8.         return substr_replace($url, $separator, $first_chunk_length, -$last_chunk_length); 
  9.     } 
  11.     return $url;
  12. }
  14. $url = '';
  15. $short_url = shorten_url($url);

With this, you can link to $url and display $short_url, and it's still pretty clear where the link takes you. Of course, you can also easily adapt it to fit any particular length, and you can even use a real ellipsis instead of ... for the separator.

I'm currently writing a test suite for comments, since I want to allow more formatting in the comments as well as maintain strict XHTML. I'm hoping to find an existing solution, but I haven't found anything yet. Once I have my criteria better defined and a decent test suite written, I'll blog more about it.