PHP不重复地回显XML属性

PHP不重复地回显XML属性,php,xml,echo,repeat,Php,Xml,Echo,Repeat,我的问题与PHP和XML有关。我想回显一些属性,但回显那些只重复一次的属性 假设这就是我正在处理的XML,它被称为beatles.XML: <XML_DATA item=“TheBeatles”> <Beatles> <Beatle Firstname=“George” Lastname=“Harrison” Instrument=“Guitar”>Harrison, George</Beatle> <Be

我的问题与PHP和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>

我希望这能呼应出吉他、吉他、贝司、鼓,但我希望吉他只显示一次。如何防止重复属性值回声?

foreach
循环中,将仪器名称转换为字符串并将其推入数组。一旦循环完成执行,您将拥有一个包含所有仪器名称的数组(当然还有重复的名称)。现在可以使用从数组中过滤出重复值:

$instruments = array();

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

$instruments = array_unique($instruments);

然后使用
foreach


要么使用。

谢谢!这让我得到了我所希望的确切结果:)
$instruments = array();

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

$instruments = array_unique($instruments);
    $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.',';
        }

}