Question

my question has to do with PHP and XML. I would like to echo out some attributes, but echo ones that repeat only once.

Say this was the XML I was dealing with, and it was called 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>

This is the PHP I have so far:

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

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

I would expect this to echo out Guitar,Guitar,Bass,Drums, but I would like Guitar to only display once. How would I prevent repeat attribute values from echoing out?

Was it helpful?

Solution

Inside the foreach loop, cast the instrument name as a string and push it into an array. Once the loop finishes execution, you will have an array containing all the instrument names (with duplicates, of course). You can now use array_unique() to filter out the duplicate values from the array:

$instruments = array();

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

$instruments = array_unique($instruments);

Demo.

OTHER TIPS

    $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.',';
        }

}

then Loop through the $result array with foreach

Either use xpath.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top