Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searching XML for value

Tags:

php

I have an XML file that returns like the following:

<games>
 <game>
  <appID>1234</appID>
  <name>game 1</name>
 </game>
 <game>
  <appID>5678</appID>
  <name>game 2</name>
 </game>
 <game>
  <appID>9123</appID>
  <name>game 3</name>
 </game>
</games>

I would like my code to get the url parameter gid to $gid, search the xml for that appid and then assign $gamename if it matches in the XML. Currently it will only work when the first game is clicked. It doesn't seem to search past the first < game >.

$gid = (int) $_GET['gid'];
$gamespage = simplexml_load_file("http://gamepage.com/games?xml=1");
$gamelist = $gamespage->games;      
if ($gid == $gamelist->game->appID) {
$appid = $gamelist->game->appID;
$gamename = $gamelist->game->name; }
else {
echo "No game stats. <br />"; }
like image 710
user1568736 Avatar asked Mar 27 '26 15:03

user1568736


1 Answers

You can do this quite easily using an XPath query:

$xpath = $gamespage->xpath('/games/game[appID = ' . $gid . ']/name');
if ($xpath) {
    $appid = $gid;
    $gamename = (string) $xpath[0];
} else {
    echo "No game stats. <br />";
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!