title: Simplexml Object Node Iteration
body: <p>I have an XML file that I'm parsing with PHP's Simplexml, but I'm having an issue with an iteration through nodes.</p>
  
  <p>The XML:</p>
  
  <pre><code>&lt;channel&gt;
    &lt;item&gt;
      &lt;title&gt;Title1&lt;/title&gt;
      &lt;category&gt;Cat1&lt;/category&gt;
    &lt;/item&gt;
    &lt;item&gt;
      &lt;title&gt;Title2&lt;/title&gt;
      &lt;category&gt;Cat1&lt;/category&gt;
    &lt;/item&gt;
    &lt;item&gt;
      &lt;title&gt;Title3&lt;/title&gt;
      &lt;category&gt;Cat2&lt;/category&gt;
    &lt;/item&gt;
  &lt;/channel&gt;
  </code></pre>
  
  <p>My counting function:</p>
  
  <pre><code>public function cat_count($cat) {
      $count = 0;
      $items = $this-&gt;xml-&gt;channel-&gt;item;
      $size  = count($items);
  
      for ($i=0; $i&lt;$size; $i++) {
          if ($items[$i]-&gt;category == $cat) {
              $count++;
          }
      }
      return $count;
  }
  </code></pre>
  
  <p>Am I overlooking an error in my code, or is there another preferred method for iterating through the nodes? I've also used a foreach and while statement with no luck, so I'm at a loss. Any suggestions?</p>
  
  <p>EDIT: while using the xpath method below, I noticed that using</p>
  
  <pre><code>foreach ($this-&gt;xml-&gt;channel-&gt;item as $item) {
      echo $item-&gt;category;
  }
  </code></pre>
  
  <p>will print all the category name, but, using</p>
  
  <pre><code>foreach ($this-&gt;xml-&gt;channel-&gt;item as $item) {
      if ($item-&gt;category == $cat) {
          echo $item-&gt;category;
      }
  }
  </code></pre>
  
  <p>will only print one instance of the doubled categories. Even when I have copy and pasted the lines, only one shows. Does this mean the XML structure could be invalid somehow?</p>