2013-12-09 36 views
1

我的問題與PHP和XML有關。我想回應一些屬性,但回顯只重複一次的屬性。PHP Echo XML屬性不重複

說,這是我處理與XML,它被稱爲beatles.xml:

<XML_DATA item=「TheBeatles」> 
    <Beatles> 
     <Beatle Firstname=「George」 Lastname=「Harrison」 Instrument=「Guitar」>Harrison, George</Beatle> 
     <Beatle Firstname=「John」 Lastname=「Lennon」 Instrument=「Guitar」>Lennon, John</Beatle> 
     <Beatle Firstname=「Paul」 Lastname=「McCartney」 Instrument=「Bass」>McCartney, Paul</Beatle> 
     <Beatle Firstname=「Ringo」 Lastname=「Starr」 Instrument=「Drums」>Starr, Ringo</Beatle> 
    </Beatles> 
</XML_DATA> 

這是PHP我到目前爲止:

$xml = simplexml_load_file("http://www.example.com/beatles.xml"); 
$beatles = $xml->Beatles->Beatle; 

foreach($beatles as $beatle) { 
echo $beatle->attributes()->Instrument.','; 
} 

我希望它可以回聲吉他,吉他,貝司,鼓,但我想吉他只顯示一次。我將如何防止重複屬性值回顯?

回答

2

foreach循環內,將儀器名稱轉換爲字符串並將其推入數組中。循環完成執行後,您將擁有一個包含所有儀器名稱的數組(當然有重複數據)。通過$result陣列foreach

要麼使用xpath

$instruments = array(); 

foreach($beatles as $beatle) { 
    $instruments[] = (string) $beatle->attributes()->Instrument; 
} 

$instruments = array_unique($instruments); 

Demo.

+0

謝謝!這讓我確切的結果,我希望:) – user1339316

1
$xml = simplexml_load_file("http://www.example.com/beatles.xml"); 
    $beatles = $xml->Beatles->Beatle; 
    $result = array(); 
    foreach($beatles as $beatle) { 

     if (!array_key_exists($beatle->attributes()->Instrument, $result)) { 
      $result[] = $beatle->attributes()->Instrument; 
      // echo $beatle->attributes()->Instrument.','; 
     } 

} 

然後循環:您現在可以使用array_unique()從數組中篩選出重複值。