views:

169

answers:

4

Hey guys, I want to parse some xml but I don't know how I can get the same tags out of 1 element.

I want to parse this:

<profile>
   <name>john</name>
   <lang>english</lang>
   <lang>dutch</lang>
</profile>

So I want to parse the languages that john speaks. how can I do that ?

+2  A: 
$profile->lang[0]
$profile->lang[1]
usoban
+1  A: 

You can run a foreach loop over the element node after you've pulled it in with SimpleXML like so:

$xml_profiles = simplexml_load_file($file_profiles);

foreach($xml_profiles->profile as $profile)
{   //-- first foreach pulls out each profile node

    foreach($profile->lang as $lang_spoken)
    {   //-- will pull out each lang node into a variable called $lang_spoken
        echo $lang_spoken;
    }
}

This has the benefit of being able to handle any number of lang elements you may have or not have for each profile element.

random
+1  A: 

Think of duplicate XML nodes as behaving like an array.

As other have pointed out you can access the child nodes with bracket syntax

myXML->childNode[childIndex]

As a side note this is how RSS feeds work. You will notice multiple

<item>
</item>

<item>
</item>

<item>
</item>

Tags within a tag of RSS XML. RSS readers deal with this problem everyday by treating the list as an array of elements.

Which can be looped over.

Gordon Potter
A: 

You can also use XPath to gather an array of specific elements like

$xProfile = simplexml_load_string("<profile>...</profile>");
$sName = 'john';
$aLang = $xProfile->xpath("/profile/name[text()='".$sName."']/lang");
// Now $aLang will be an array of lang *nodes* (2 for John). Because they
// are nodes you can still do SimpleXML "stuff" with them i.e.
// $aLang[0]->attributes(); --which is an empty object
// or even

$sPerson = (string)$aLang[0]->xpath('preceding-sibling::name');
// of course you already know this... but this was just to show what you can do
// with the SimpleXml node.
null