Using Variables in Simplexml

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
MikeEller
Forum Newbie
Posts: 11
Joined: Sun Feb 05, 2006 3:43 pm

Using Variables in Simplexml

Post 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
hairytea
Forum Commoner
Posts: 92
Joined: Mon Feb 04, 2008 8:31 am

Re: Using Variables in Simplexml

Post 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. :-)
MikeEller
Forum Newbie
Posts: 11
Joined: Sun Feb 05, 2006 3:43 pm

Re: Using Variables in Simplexml

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Using Variables in Simplexml

Post by requinix »

You're venturing into the territory of variable variables.

Code: Select all

$xml->{$country}->name
Post Reply