tags:

views:

59

answers:

3

I am beginner in PHP. I am trying to parse this xml file.

<relationship>
 <target>
  <following type="boolean">true</following>
  <followed_by type="boolean">true</followed_by>
  <screen_name>xxxx</screen_name>
  <id type="integer">xxxx</id>
 </target>
 <source>
  <notifications_enabled nil="true"/>
  <following type="boolean">true</following>
  <blocking nil="true"/>
  <followed_by type="boolean">true</followed_by>
  <screen_name>xxxx</screen_name>
  <id type="integer">xxxxx</id>
 </source>
</relationship>

I need to get the value of the field 'following type="boolean" ' for the target and here's my code -

$xml = simplexml_load_string($response);

foreach($xml->children() as $child)
{
      if ($child->getName() == 'target')
      {
       foreach($child->children() as $child_1)
       if ( $child_1->getName() == 'following')
       {
        $is_my_friend = (bool)$child_1;
        break;
       }
       break;
      }
}

but I am not getting the correct output. I think the ' type="boolean" ' part of the field is creating problems. Please help.

+1  A: 

$xml = simplexml_load_string($response);

foreach($xml->target->following as $child) { $is_my_friend = $child; }

Jamie
+4  A: 

You could also use xpath for this.

foreach ($xml->xpath("//target/following[@type='boolean']") as $is_my_friend) 
{   
  echo $is_my_friend;
}
Greg W
+1  A: 

When casting a string to boolean in PHP, all values except the empty string and "0" are considered TRUE.

http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

ecounysis
Er, according to your link, your answer isn't correct. All values are considered *true*, except the empty string, "0", and the others in that list.
zombat
@zombat good catch
ecounysis