Tuesday, May 25, 2010

JavaRanch Flair

Check out my JavaRanch flair!



I was so inspired by the flair over at Stackoverflow that I thought it would be fun to create my own! It basically works just like Stackoverflow's does. You have three options for how to include it in your webpage:

  • Javascript - You can include it using a <script> tag, which injects the flair into the DOM via Javascript.
    <script
      src="http://www.mangst.com/flair/javaranch?id=209694&type=js"
      type="text/javascript">
    </script>
    
  • HTML - You can include it using an <iframe>, which loads the flair as HTML into the frame.
    <iframe
      src="http://www.mangst.com/flair/javaranch?id=209694&type=html"
      marginwidth="0"
      marginheight="0" 
      frameborder="0"
      scrolling="no"
      width="220"
      height="100">
    </iframe>
    
  • JSON - You can get the raw data with JSON and handle the data however you wish with Javascript.
    JSON URL: http://www.mangst.com/flair/javaranch?id=209694&type=json
On the backend, what it does is it screen scrapes your JavaRanch profile page, plucking out the information that it needs. It uses a PHP DOMDocument object to load the HTML, then uses XPath to get the data fields.
$html = new DOMDocument();
$html->loadHtmlFile("http://www.coderanch.com/forums/user/profile/$id");
$xpath = new DOMXPath($html);
$username = $xpath->query("//span[@id='profileUserName']")->item(0)->textContent;
//...

I think it's pretty elegant, though it will break if JavaRanch decides to do any site redesigns. I was afraid that it wouldn't be able to load the HTML into a DOM, since webpage HTML tends not to be well formed XML, which would have prevented me from using XPath. The SimpleXMLElement class wouldn't accept the HTML, but the DOMDocument class did.

2 comments:

Anonymous said...

Hi,
I'm looking forward to achieve SCJP for Java 6 platform. Can you suggest me one book that can be useful for my preparation?
Thank you!

Michael Angstadt said...

Thanks for commenting at my blog! I would suggest the following book: A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer by Khalid Mughal and Rolf Rasmussen. This is what I used to prepare for the exam and I liked it very much.