Welcome to my site

Post statistics

PHP class: SimpleXML

One thing I have found is the lack of really simple XML classes—that’s not to say there aren’t any good ones out there, I have used several really cracking ones. For my new version of my personal site (yes, this site is planned for a revamp) I wanted to integrate my Twitter feed somewhere. I looked and looked for a really simple XML class but was unable to find one. So I made one. And here is the result:

The code

<?php
/**
 * @author Christopher Hill
 * @copyright (c) Christopher Hill
 * @package chrisjhill
 * @version 0.2
 */
class myXmlParser
{
   /**
    * The URL to the XML source
    * @access private
    * @var string
    */
   private $_url;
 
   /**
    * Whether or not to add this value
    * @access private
    * @var boolean
    */
   private $_ignore = false;
 
   /**
    * The attributes to allow to be added
    * @access private
    * @var array
    */
   private $_want = array();
 
   /**
    * The XML Parser class
    * @access private
    * @var object
    */
   private $_xml_parser;
 
   /**
    * The result set of the parsing
    * @access private
    * @var array
    */
   private $_return = array();
 
   /**
    * The class constructor
    * @access public
    */
   public function __construct($url) {
      $this->_url = $url;
      $this->_xml_parser = xml_parser_create();
      xml_set_element_handler($this->_xml_parser,
         array($this, 'startTag'),
         array($this, 'endTag'));
      xml_set_character_data_handler($this->_xml_parser,
         array($this, 'contents'));
   }
 
   /**
    * Set a wanted attribute
    * @access public
    * @param mixed $want
    */ 
   public function setWant($want) {
      if (is_array($want)) {
         foreach ($want as $value) {
            $this->_want[] = $value;
         }
      }
      else {
         $this->_want[] = $want;
      }
      return $this;
   }
 
   /**
    * Set the ignore
    * @access private
    * @param boolean $ignore
    */
   private function setIgnore($ignore) {
      $this->_ignore = (bool)$ignore;
      return $this;
   }
 
   /**
    * Returns the ignore variable
    * @access private
    * @return boolean
    */
   private function getIgnore() {
      return $this->_ignore;
   }
 
   /**
    * Return the want array
    * @access private
    * @return array
    */
   private function getWant() {
      return (array)$this->_want;
   }
 
   /**
    * Parses the XML input
    * @access public
    */
   public function parse() {
      $fp = fopen($this->_url, "r"); 
      $data = fread($fp, 80000);
 
      if(!(xml_parse($this->_xml_parser, $data, feof($fp)))){ 
          die("Error on line " . xml_get_current_line_number($this->_xml_parser)); 
      }
   }
 
   /**
    * Set whether to output this attribute
    * @access private
    * @param object $parser
    * @param string $data
    */
   private function startTag($parser, $data){ 
      $this->_ignore = in_array(strtolower($data), $this->getWant())
          ? true
          : false;
   } 
 
   /**
    * This function does nothing, but is needed to stop parse errors
    * @access private
    * @param object $parser
    * @param string $data
    */
   private function endTag($parser, $data){ 
      // Do nothing
   }
 
   /**
    * Echo out the contents of the atttribute
    * @access private
    * @param object $parser
    * @param string $data
    */
   private function contents($parser, $data){ 
      $data = trim($data);
      if ($this->_ignore && !empty($data)) {
         if (count($this->_return[(count($this->_return) - 1)]) == count($this->_want)) {
            $this->_return[count($this->_return)][] = $data;
         }
         else {
            $this->_return[(count($this->_return) == 0 ? 0 : count($this->_return) - 1)][] = $data;
         }
      }
   }
 
   /**
    * Return the output array
    * @access public
    * @return array
    */
   public function getReturnArray() {
      return $this->_return;
   }
}

And you use it like this

<?php
$myXmlParser = new myXmlParser('http://twitter.com/statuses/user_timeline/chrisjhill.xml');
$myXmlParser->setWant(array('text', 'created_at'))->parse();
echo '<code>';
   print_r($myXmlParser->getReturnArray());
echo '</code>';

Which will produce the following result:

Array
(
    [0] => Array
        (
            [0] => Tue Mar 25 16:24:41 +0000 2008
            [1] => Just got back from a challenging run, don't feel too tired though...
        )
 
    [1] => Array
        (
            [0] => Mon Feb 25 18:14:21 +0000 2008
            [1] => I'm fixing my XML parser class. It's better than I remember, I might consider posting it on my blog!
        )
 
    [2] => Array
        (
            [0] => Sat Jan 19 21:44:14 +0000 2008
            [1] => I cannot believe it. My se7ev DVD has had its end corrupted. 1 hour 40 of my life wasted...
        )
 
)

Now thats some nice output

I love working with arrays, the more complex they are the better. This one is quite simple though, it adds each feed into a array index which has 2 children; the date posted and the content. Simple.

A little information on using it

The class works by first supplying a URL to the XML source in the constructor. You then set what fields you want to save, and discard the rest. This saves memory without having to store data you will not use. Call the parse() function and it will work its magic. And yes, the class can make use of method chaining. Enjoy.

Date posted April 2nd, 2008
Comments Disabled
Categories PHP
Author Christopher Hill

I'm Christopher. A twenty-something graduate, star gazer, aspiring triathlete, vegetarian, reader and writer, cinemaniac and lover of life in general

From the journal

From the deep

Obligatory links

Create simple UML diagrams on-the-fly

yUML is an online tool for creating and publishing simple UML diagrams. It’s makes it really easy for you to: Embed UML diagrams in blogs, emails and wikis, Post UML diagrams in forums and blog comments, Use directly within your web based bug tracking tool and Copy and paste UML diagrams into MS Word documents and Powerpoint presentations.

Javascript Tidy

One thing I often need to do is to tidy javascript from it’s packed state. Often to fix the developers bugs, add new features or to modify it slightly. I give you, the Javascript Tidy, a tool I couldn’t live without.

jQuery Slider plugin (Safari style)

A pretty awesome slider. Haven’t tried it out yet but the new version seems pretty easy to skin, so you can style it however-the-hell you want (note: click the ‘jQuery Slider update’ link).

MySQL Format Date

MySQL Format Date helps you format your dates using the MySQL DATE_FORMAT function. Just select a common date format and then change it to your suit your needs. The MySQL DATE_FORMAT code will be generated at the bottom of the page which you can then copy into your query.

The future of wireframes?

I have a love hate relationship with wireframes. In the last 10 years they’ve been a part of every web project I’ve worked on. There have been times when I can’t imagine how we would have solved a particular problem without them. Yet there are also times when I’ve been completely exasperated at the amount of time and energy they’ve consumed, seemingly to very little reward.

So you need a typeface?

A pretty humorous look into how you could choose your typeface for your next project.

New global visual language for BBC

We decided to embark on an ambitious project, called Global Visual Language 2.0, with the aim of unifying the visual and interaction design of bbc.co.uk and the mobile website.

jQuery plugin: Nivo Slider

A really cool image slider than has some unique transitional effects without using Flash.

MooTools plugin: DatePicker

jQuery has the best functioning plugins. MooTools has the best looking plugins. Whenever I want to add in a datepicker I always find this and think: “Oooh. Pretty. Do want.”. Then realise it’s MooTools only. Real shame.

jQuery plugin: Sparklines

I know, I know. This plugin has been around for, what seems like, years. But I thought I would give it a little bit of a spotlight. And yes, so I can easily find it again.

jQuery plugin: asmSelect

asmSelect is a jQuery plugin providing progressive enhancement to select multiple form elements. It provides a simpler alternative with several advantages. This new version includes several bug fixes and enhancements.

How coupon codes can lead to lost revenue

In this post we’ll be looking at how coupon codes (used synonymously here with promo and discount codes) can cause retailers to lose revenue. I’ll share some (hopefully) interesting trends that I’m seeing with a client I work with, and hopefully start a discussion with how to turn lost revenue into gained revenue.

A good browser should be able to reproduce itself

This is an interesting project which aimes to completely reproduce the visual aspect of Safari in pure HTML+CSS with zero images. There are a few caveats at the moment, such as no refresh button, but they say they are working on it. Once again this really shows the power that HTML5 and CSS3 brings to the Web.

jQuery plugin: gameQuery

gameQuery is a jQuery plug-in to help make javascript game development easier by adding some simple game-related classes. It’s still in an early stage of development and may change a lot in future versions.

CSS/Javascript Word Clock

A lit­tle ex­per­i­ment I built: a word clock using CSS3 trans­forms and a lit­tle Javascript to run the ac­tu­al clock. Use­ful? Maybe not. Fun? Def­i­nite­ly.

CSS Border Radius Web Page

It’s one of those things that makes you think “Doh! I should have made that agaes ago”. A simple Web page that allows you to simply get the CSS for the exact border radius you want.

The main thing is not to install Flash

A security expert who has won the Pwn2Own contest for 2 years running said, basically, that Flash is insecure. Well, we all knew that which is why we add Flashblock and the like. Right?

Pure CSS3 Bokeh effect

One of the best apps made using CSS3, that’s for sure. A few more options would be nice, such as changing colours of the circles and being able to place them manually.

EZ-CSS: An easy to use, lightweight, CSS framework

It is light (1kb), flexible, browser-friendly and easy to use! ez-css is a different kind of CSS framework. Authors are not bound to a “grid”. Plus, columns and gutters can be of any width.

jQuery plugin: Quicksand

I love Mac apps, especially for their attention to detail. CoreAnimation makes it so easy to create useful and eye-pleasing effects. Quicksand aims at providing a similar experience for users on the web.