Page 1 of 1

Using Variables in Simplexml

Posted: Fri Jan 22, 2010 7:09 am
by MikeEller
Hi,

I want to be able to use a variable in simplexml statement like this:

$thename = $_GET['NAME'];
$xml = simplexml_load_file("countries.xml");
$thename = $xml->$country->name;

however, it does not allow me to use the variable ($country) this way. Is there a way to do this?
I need to be able to select which country I am working with based on the user's selection.

Thanks,
Mike

Re: Using Variables in Simplexml

Posted: Fri Jan 22, 2010 7:24 am
by hairytea
i'm not 100% sure as have never used xml with php and am learning myself but....would you not concatenate the $country variable?

THIS...

Code: Select all

 
$thename = $xml.$country->name;
 
INSTEAD OF...

Code: Select all

 
$thename = $xml->$country->name;
 

???

It is a wild guess so apologies if incorrect. :-)

Re: Using Variables in Simplexml

Posted: Fri Jan 22, 2010 7:59 am
by MikeEller
No that did not work.

If I hard code it, it looks like this

Code: Select all

<img src="<?php echo $xml->bolivia[0]->flag->path; ?> />
And this works.....

What I need to do is use a variable in place of bolivia.....like this:

Code: Select all

<img src="<?php echo $xml->$country[0]->flag->path; ?> />
Where $country is variable containing the name of a country in string form.

Mike

Re: Using Variables in Simplexml

Posted: Fri Jan 22, 2010 8:10 am
by requinix
You're venturing into the territory of variable variables.

Code: Select all

$xml->{$country}->name