title: get HTML element by attribute value in php
body: <p>I need to extract some data from a webpage with php. The part that I'm interested in is structured similarly to this:</p>
  
  <pre><code>&lt;a href="somepath" target="fruit"&gt;apple&lt;/a&gt;
  &lt;a href="somepath" target="animal"&gt;cat&lt;/a&gt;
  &lt;a href="somepath" target="fruit"&gt;orange&lt;/a&gt;
  &lt;a href="somepath" target="animal"&gt;dog&lt;/a&gt;
  &lt;a href="somepath" target="fruit"&gt;mango&lt;/a&gt;
  &lt;a href="somepath" target="animal"&gt;monkey&lt;/a&gt;
  </code></pre>
  
  <p>First, I want to extract all fruits, and then all animals, so that I have them nicely grouped.</p>
  
  <p>I figured out how to loop through all attribute values. Here's the code:</p>
  
  <pre><code>$dom = new DOMDocument();
  $html = file_get_contents('example.html');
  
  @$dom-&gt;loadHTML($html);
  
  $a = $dom-&gt;getElementsByTagName('a');
  
  for ($i; $i &lt; $a-&gt;length; $i++) {
  $attr = $a-&gt;item($i)-&gt;getAttribute('target');
  
  echo $attr . "\n";
  }
  </code></pre>
  
  <p>So I get:</p>
  
  <pre><code>fruit animal fruit animal fruit animal
  </code></pre>
  
  <p>I also found out how to get the elements' text content:</p>
  
  <pre><code>$a-&gt;item($i)-&gt;textContent
  </code></pre>
  
  <p>So, if included in loop and echoed, I get:</p>
  
  <pre><code>apple cat orange dog mango monkey
  </code></pre>
  
  <p>I feel like I'm very close, but I can't get what I want. I need something like this:</p>
  
  <p>if ( target = "fruit") then give me "apple, orange, mango".</p>
  
  <p>Can someone please point me in the right direction?</p>
  
  <p>Thanks.</p>