Dessert #14 - The new Xml class

Posted by Felix Geisendörfer, on Sep 21, 2006 - in PHP & CakePHP » Core & Hacking

Deprecated post

The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.

Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.

Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).

This is going to be my first 1.2 dessert, I hope the 1.1 people don't mind it, in case you really want to use it in your current application, you can grab the Xml class itself from the 1.2 branch and put it into the vendors folder.

One of the very cool things that's going to ship with the new release is a new Xml class that can parse any given Xml document for you, which is a really nice thing to have, especially if you manually parsed Xml before like I did.

I was thinking about how to show it's functionality best, and I think the good old RSS example will do the job. So in order to fully appriciate it, take a look at the code of my RssModel needed to parse an Rss feed. After that look at a very quick & dirty example of displaying an Rss feed using the new Xml class of 1.2:

Fetch the feed like this in the Controller:

php
  1. class XmlTestController extends AppController
  2. {
  3.     var $name = "XmlTest";
  4.     var $uses = array();
  5.  
  6.     function index()
  7.     {
  8.         uses('Xml');
  9.         $Feed =& new XML('http://www.thinkingphp.org/feed/');
  10.        
  11.         $this->set('Feed', $Feed);
  12.     }
  13. }

And then display it in the View:

php
  1. <?php if ($Node->name=='item'): ?>
  2.     <h2><?php $Title = $Node->getChild('title'); echo $Title->value; ?></h2>
  3.     <p>
  4.         <?php $Description = $Node->getChild('description'); echo $Description->value; ?>
  5.     </p>
  6. <?php endif; ?>

That's it, you already parsed an entire Rss feed and displayed all it's item in a simple headline/paragraph chain. Now imagine how easy it'll be to work with web services using the power of this class ; ). I'm talking with nate about this kind of stuff right now, and it looks like CakePHP will get a couple new datasources in 1.2 for this as well, but I'll write more about this once the Api for it get's more stable. However, one thing is for sure: We'll not need to extend the Model class any more to emulate different data sources in 1.2.

--Felix Geisendörfer aka the_undefined