Jump to content

Problems parsing XML using PHP


willsko87

Recommended Posts

Hi,

 

I am trying to pull some information from an xml file but I am having trouble trying to access some values. There are two <stats> sections but I can only seem to access the second one.

 

Here is the XML file:

 

<game_live>

  <stats team="h">
    <player name="A Player" shortname="a" num="10" id="250365" pos="INT" k="8" h="10" m="7" t="4" ho="0" ff="2" fa="1" g="0" b="0" in50="2" rankingpoints="87" fantasypoints="80"/>
  </stats>
  <stats team="a">
    <player name="B Player" shortname="b" num="44" id="220009" pos="CHB" k="14" h="12" m="6" t="1" ho="0" ff="0" fa="1" g="0" b="0" in50="1" rankingpoints="92" fantasypoints="85"/>
    </stats>
    

 

I am trying to get the players name under the first stats section. This would be 'A Player' but I cannot work out how to get it. Below is the code I've used .

 

 

<?php 
$xmlFileData = file_get_contents("match-10250605.xml");
$xmlData = new SimpleXMLElement($xmlFileData);


foreach($xmlData->stats[0] as $stats1) {

$name = $stats1->player[0]["name"];

}

echo "Name: ".$name;

?>

 

For some reason there is no output. If I put in just 'stats' instead of 'stats[0]' then it goes straight the second stats section and outputs that players name 'B Player'.

 

What am I doing wrong?

Link to comment
https://forums.phpfreaks.com/topic/191018-problems-parsing-xml-using-php/
Share on other sites

The problem is that you're only echoing the last value found, effectively ignoring any others. With stats[0] you only target the first stats, without the [0] you target them all but only ever keep a note of the last one which is echoed outside of the loop.  Change your foreach loop such that each item gets echoed within the loop, or you store an array of names for use later.

 

foreach ($xmlData->stats as $stats1) {
    echo "Name: " . $stats1->player[0]["name"];
}

Ok that works. It ends up outputting the first 'name' from each. Thanks for that.

 

Ultimately I would like to output the name of the players (attribute "name") in order of how many goals they have scored (attribute "g"). Any ideas how I would go about doing this?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.