Filtering XML results in PHP

Hello Kirupans,

I have another post here regarding a PHP/XML issue I ran into, but I’m going to start a new topic here since I feel this is a question that deserves one. Why? Well because it’s quite a mouthful.

I’m in the process of creating a page that displays multiple lines of inventory for a bunch of products (let’s call them ‘widgets’). The widgets are listed in XML format (they’ll end up being pulled from a MySQL DB eventually).

<inventory>
   <widget>
      <name>One</name>
      <color>Red</color>
      <weight>5</weight>
      <price>15</price>
   </widget>
   <widget>
      <name>Two</name>
      <color>Blue</color>
      <weight>8</weight>
      <price>21</price>
   </widget>
   <widget>
      <name>Three</name>
      <color>Green</color>
      <weight>3</weight>
      <price>12</price>
   </widget>
   <widget>
      <name>Four</name>
      <color>Red</color>
      <weight>15</weight>
      <price>35</price>
   </widget>
</inventory>

Now, I have a PHP page that opens up my XML file using SimpleXML:

<?php 
$xml =  simplexml_load_file('inventory.xml');
?>

Then it will display information for each widget in a nice, neat format:

<?php
foreach ($xml->widget as $widget) {
    echo "<div class='widget'>";
    echo "<span class='name'>" . $widget->name . "</span>";
    echo "<span class='color'>" . $widget->color . "</span>";
    echo "<span class='weight'>" . $widget->weight . "</span>";
    echo "<span class='price'>" . $widget->price . "</span>";
    echo "</div>";
}
?>

My question to you is, how would I go about building a function that would filter the results to this page. For instance if there was a set of check-boxes that allowed you to only display the “Red” or “Blue” colored widgets. Or perhaps I only want to see “Red” widgets that have a price less than “20”.

Any help or pointers are completely appreciated. Thanks in advance Kirupans!