2015-02-12 23 views
1

我有一個XML字符串,我試圖提取兒童標籤的名稱。每個兒童標籤都是自動關閉的。我試圖用SimpleXMLElementXML:PHP只解析一系列的兒童中的第一個

$xml_str = '1<?xml version="1.0" encoding="UTF-8"?><parent><personal_data><child1 attr="sth /><child2 attr=sth2/></personal_data><personal_data><child1 attr="sth /><child2 attr=sth2/></personal_data</parent>'; 

$sxe = new SimpleXMLElement($xml); 

//get the children from the parent 
$sxe = $sxe->children(); 
echo $sxe; 
$form_mappers = array(); 
foreach ($sxe->children() as $child){ 
    array_push($form_mappers, $child->getName()); 
}   

echo var_dump($form_mappers); //only children from the first parent 

這僅獲得第aParent節點的孩子。爲什麼我不能得到第二個孩子的節點?

+0

@Ghost我認爲,任何畸形的產物我把一個樣本放在一起。這個驗證器http://xmlgrid.net/validator.html說我的實際XML是有效的。 – 1252748 2015-02-12 00:10:04

+0

無論如何預期輸出是什麼? 4個孩子?你需要循環內eeach個人資料 – Ghost 2015-02-12 00:11:04

+0

是啊,四個孩子'child1,child2,child1,child1' – 1252748 2015-02-12 00:12:37

回答

1

如果你想獲得的所有<child*>節點,你需要遍歷每個<personal_data>也得到內部級內部:

$form_mappers = array(); 
foreach ($sxe->children() as $personal_data){ 
    foreach($personal_data->children() as $child) { 
     $form_mappers[] = $child->getName(); 
    } 
} 

Sample Output

+0

這是完美的。非常感謝你。 – 1252748 2015-02-12 00:23:46

+0

@ thomas肯定我很高興這有幫助 – Ghost 2015-02-12 00:24:44

+0

回想起來,這似乎很明顯。我想我的主要問題是:爲什麼我的代碼檢索'child1','child2',而不是'personal_data','personal_data'? – 1252748 2015-02-12 15:15:11