Manipulating XML element data, softcode element names

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
DaveF
Forum Newbie
Posts: 3
Joined: Tue Dec 16, 2008 5:42 am

Manipulating XML element data, softcode element names

Post by DaveF »

Hi All,

Wonder if you can help.

I know that you can update XML element data by hardcoding the element names, eg:

Code: Select all

 
$xml = new SimpleXMLElement($xmlstr); 
$xml->element1->element2->element3 = 'Hello World'; 
 
Problem I have is that the code I am writing is going to be used to process many different XML files and as such I won't know the element names until runtime and as such I can't hard code the updates as above.

So my query is this: is there a way to update element data using $variables to identify the element names?

Apologies if this is a repeat post.

Many thanks
Dave
DaveF
Forum Newbie
Posts: 3
Joined: Tue Dec 16, 2008 5:42 am

Re: Manipulating XML element data, softcode element names

Post by DaveF »

Had a think and some more info on the problem may help.

My script receives an XML file. That could be any number of different XML files.
In this example let's assume the file is XMLFileA.xml

I build a form based on the contents of XMLFileA.xml with the element names as the <input> names and the element data as the <input> values.

The user is then free to alter the <input> values and submit the form.

This submitted form is then $_POSTed to the script and the aim of the script is to copy XMLFileA.xml into a new file (XMLFileB.xml) and then update the element data with the values defined in by the user, from the form.

I'll know the element names once I receive XMLFileA.xml but I don't know them before this (as the xml could be any one of a number of XML files) and as such I can't hard code the updates as in my previous post.

Any help very gratefully received.

Thanks
Dave
DaveF
Forum Newbie
Posts: 3
Joined: Tue Dec 16, 2008 5:42 am

Re: Manipulating XML element data, softcode element names

Post by DaveF »

Solution is this:

$foo = 'element1';
$xml->{$foo}->element2 = "Hello!";

Thanks
Dave
Post Reply