Search code examples
phpxmlxml-parsingfeed

How to get the item attribute of an xml file, when the the number of items within a tag is always changing


I have this bit of xml code below and I'm trying to get the value of all of the "result value" attributes within the results tag. The thing is...this is going to be a live feed, so there may be 1,2 or 3 result items within that tag.

Do I need to do some sort of count to see how many items are within the results tag?

<Match ct="0" id="771597" LastPeriod="2 HF" LeagueCode="19984" LeagueSort="1" LeagueType="LEAGUE" startTime="15:00" status="2 HF" statustype="live" type="2" visible="1">
    <Home id="11676" name="Manchester City" standing="1"/>
    <Away id="10826" name="Newcastle United" standing="3"/>
    <Results>
        <Result id="1" name="CURRENT" value="1-1"/>
        <Result id="2" name="FT" value="1-1"/>
        <Result id="3" name="HT" value="1-0"/>
    </Results>
    <Information>
        <league id="19984">Premier League</league>
        <note/>
        <bitarray/>
        <timestamp/>
    </Information>
</Match>

Thanks in advance


Solution

  • SimpleXML

    Just loop through the results with SimpleXML to grab each value and name attribute, this will work with a variable number of results.

    Demo

    $obj = simplexml_load_string($xml);
    
    foreach($obj->Results->Result as $result)
    {
        echo $result->attributes()->name . ': ' . $result->attributes()->value . "\n";
    }
    

    Outputs

    CURRENT: 1-1
    FT: 1-1
    HT: 1-0

    If you have a root node such as Matches with multiple Match under it then you would use a nested foreach like so:

    foreach($obj->Match as $match)
    {
        foreach($match->Results->Result as $result)
        {
            echo $result->attributes()->name . ': ' . $result->attributes()->value . "\n";
        }
    }
    

    DOMDocument

    To do the same using DOMDocument instead of SimpleXML:

    $dom = new DOMDocument();
    $dom->loadXML($xml);
    
    foreach($dom->getElementsByTagName('Match') as $match)
    {
        foreach($match->getElementsByTagName('Result') as $result)
        {
            echo $result->getAttribute('name') . ': ' . $result->getAttribute('value') . "\n";
        }
    }
    

    Outputs the same as the SimpleXML method.