2009-07-16 125 views
2

嘿傢伙,我想解析一些XML,但我不知道如何從1個元素中獲得相同的標籤。SimpleXML更多標籤在1個元素

我要分析此:

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

所以我想解析約翰講的語言。我怎樣才能做到這一點 ?

回答

2

可以運行foreach循環元素節點在你用SimpleXML拉昇後,在像這樣:

$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; 
    } 
} 

這具有能夠處理任意數量的lang元素的好處您可能有或沒有爲每個配置文件元素。

2
$profile->lang[0] 
$profile->lang[1] 
1

將重複的XML節點看作行爲像一個數組。

正如其他人指出,你可以用括號的語法

myXML->childNode[childIndex] 

訪問子節點作爲一個方面說明,這是RSS提要如何工作。您會注意到多個

<item> 
</item> 

<item> 
</item> 

<item> 
</item> 

RSS XML標籤內的標籤。 RSS閱讀器通過將列表視爲一組元素來處理這個問題。

可以循環。

0

您還可以使用XPath來收集特定元素的數組一樣

$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.