2013-11-25 89 views
0

我使用SimpleXML並希望得到每個不同learner及其子rater屬性,我怎麼能解析它變成像一個單獨的:PHP的SimpleXML搶屬性

Learner: John 

Rater_1_name: John 
Rater_1_email: [email protected] 
Rater_1_group: Self 

Rater_2_name: Jane 
Rater_2_email: [email protected] 
Rater_2_group: Manager 

Rater_3_name: Nathan 
Rater_3_email: [email protected] 
Rater_3_group: Peers 

// and so on... 

代碼解析:

$xml = ' 
<users> 
    <learner name="John"> 
     <rater name="John" email="[email protected]" group="Self"></rater> 
     <rater name="Jane" email="[email protected]" group="Manager"></rater> 
     <rater name="Nathan" email="[email protected]" group="Peers"></rater> 
    </learner> 
    <learner name="Jane"> 
     <rater name="Jane" email="[email protected]" group="Self"></rater> 
     <rater name="John" email="[email protected]" group="Peers"></rater> 
     <rater name="Nathan" email="[email protected]" group="Others"></rater> 
    </learner> 
</users> 
'; 

$sxe = new SimpleXMLElement($xml); 
echo $sxe->asXML(); 

謝謝。

回答

0

您可以在foreach()循環中訪問您的元素,因爲SimpleXMLElement實現了Traversable接口。所以,這些方針的東西應該讓你開始: -

$xml = ' 
<users> 
    <learner name="John"> 
     <rater name="John" email="[email protected]" group="Self"></rater> 
     <rater name="Jane" email="[email protected]" group="Manager"></rater> 
     <rater name="Nathan" email="[email protected]" group="Peers"></rater> 
    </learner> 
    <learner name="Jane"> 
     <rater name="Jane" email="[email protected]" group="Self"></rater> 
     <rater name="John" email="[email protected]" group="Peers"></rater> 
     <rater name="Nathan" email="[email protected]" group="Others"></rater> 
    </learner> 
</users> 
'; 

$sxe = simplexml_load_string($xml); 

foreach($sxe as $learner){ 
    $attr = $learner->attributes(); 
    $name = $attr['name']; 
    echo "Learner $name <br/>Rated by:-<br/>\n"; 
    foreach($learner->rater as $rater){ 
     foreach($rater->attributes() as $key => $value){ 
      echo " - $key = $value <br/>\n"; 
     } 
    } 
} 

輸出: -

Learner John 
Rated by:- 
- name = John 
- email = [email protected] 
- group = Self 
- name = Jane 
- email = [email protected] 
- group = Manager 
- name = Nathan 
- email = [email protected] 
- group = Peers 
Learner Jane 
Rated by:- 
- name = Jane 
- email = [email protected] 
- group = Self 
- name = John 
- email = [email protected] 
- group = Peers 
- name = Nathan 
- email = [email protected] 
- group = Others 

See it working