使用SimpleXml访问PHP的第n个XML元素

I have an xml formatted like this:

<?xml version="1.0"?>
<root>
  <foo id="1">
    <bar>text</bar>
  </foo>
  <foo id="2">
    <bar>text2</bar>
  </foo>
</root>

I know that, in PHP, you I can access the nth element of an xml file loaded with SimpleXML like so:

$xml = simplexml_load_file('file.xml');
echo $xml->foo[2]->bar;

but I need to access an element by a variable pulled from $_GET, so:

echo $xml->foo[$var]->bar;

This doesn't seem to work, and I'd really appreciate any advice. Thanks!

It seems SimpleXML distinguishes between numeric and non-numeric array offsets in a slightly different way to a normal PHP array, so you need to cast your variable to an integer first. (All input from the query string is a string until you tell PHP otherwise.)

$var = intval($_GET['var']);
echo $xml->foo[$var]->bar;

This will turn the string '1' into the integer 1, and should give the result you require.