Search code examples
phpxmlsimplexml

Get only attributes if another attribute has specific value


Ok, first question on stackoverflow.

I have the following xml:

<movies>
  <movie>
    <cast>
      <person name="Tim Johnson" character="" job="Director"/> 
      <person name="Avril Lavigne" character="Heather (voice)" job="Actor"/> 
      <person name="Omid Djalili" character="Tiger (voice)" job="Actor"/>
      <person name="Karey Kirkpatrick" character="" job="Director"/>
    </cast>
  </movie>
</movies>

I retrieve it like this:

<?php $xml_getinfo_result = new SimpleXMLElement(file_get_contents($tmdb_getinfo_result)); ?>

To get the cast, I use the following:

$i = 0;
while ($xml_getinfo_result->movies->movie->cast->person[$i]) {
  $tmdb_actors = $xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->name;
  echo "<li>".$tmdb_actors."</li>";
$i++;
}

This gives me:

<li>Tim Johnson</li>
<li>Avril Lavigne</li>
<li>Omid Djalili</li>
<li>Karey Kirkpatrick</li>

But what do I need to do if I want to display only the persons whose job is "Actor"?


Solution

  • you can do this:

    $i = 0;
    while ($xml_getinfo_result->movies->movie->cast->person[$i]) {
      $tmdb_job = $xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->job;
      if($tmdb_job == 'Actor'){
         $tmdb_name = $xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->name;
         echo "<li>".$tmdb_name."</li>";
      }
    $i++;
    }