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.
  • HTML - You can include it using an <iframe>, which loads the flair as HTML into the frame.
  • 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();
$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.


Anonymous said...

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!

mangst 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.