title: php DOM getAttribute
body: <p>Alright, so I have an odd case here that I just can't figure out.</p>
  
  <p>I want to parse a list on a website. The HTML looks somewhat like this:</p>
  
  <pre><code>&lt;!-- ... --&gt;
  &lt;ul id="foo"&gt;
      &lt;li data-text="item 1"&gt;Blabla&lt;/li&gt;
      &lt;li data-text="item 2"&gt;Blabla&lt;/li&gt;
      &lt;li data-text="item 3"&gt;Blabla&lt;/li&gt;
      &lt;li data-text="item 4"&gt;Blabla&lt;/li&gt;
  &lt;/ul&gt;
  &lt;!-- ... --&gt;
  </code></pre>
  
  <p>Now I want to grab all the list items. I use the DOMDocument-class for that. So far, that works out just fine:</p>
  
  <pre><code>$dom = new DOMDocument();
  
  if (!$dom-&gt;loadHTML($html)) {
      die ('Could not parse...');
  }
  
  $list = $dom-&gt;getElementById('foo');
  $items = $list-&gt;childNodes;
  foreach ($items as $item) {
       print_r($item);
  }
  </code></pre>
  
  <p>But now, I'm looking for a simple method to read out the <code>data-text</code> attribute. What I did was:</p>
  
  <pre><code>foreach ($items as $item) {
       echo $item-&gt;getAttribute('data-text');
  }
  </code></pre>
  
  <p>This works just fine for the very first item, but then it crashes the foreach-loop. The output is:</p>
  
  <blockquote>
    <p>item 1<br>
    Fatal error: Call to undefined method DOMText::getAttribute()
    in example.php on line 44</p>
  </blockquote>
  
  <p>What I don't get here is how calling the <code>getAttribute</code> method changes the context of the foreach loop. So here are two questions:</p>
  
  <ol>
  <li>How can invoking the method screw up my foreach loop? Secondly,
  what's the most elegant workaround?</li>
  <li>I realized I could loop through <code>$item-&gt;attributes with</code> yet another
  foreach method, then compare the attribute name to <code>data-text</code> and
  read the value in case of a match, but there surely has to be a
  better way to do so?!</li>
  </ol>