Page 1 of 1

Manipulating XML element data, softcode element names

Posted: Tue Dec 16, 2008 5:57 am
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

Re: Manipulating XML element data, softcode element names

Posted: Tue Dec 16, 2008 10:49 am
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

Re: Manipulating XML element data, softcode element names

Posted: Tue Dec 16, 2008 11:32 am
by DaveF
Solution is this:

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

Thanks
Dave