Please be aware that using eval
is dangerous to the point of insanity. What if someone somehow sets $data['main_deal']
to exec("rm -rf .")
or mysql_query('drop table users')
. You must be absolutely certain that this string cannot be tainted in any way for this to be safe. This is non-trivial, as most filters are geared toward preventing XSS injection, and not this type of attack.
I don't mean to be a jerk, I realize you're just trying to get a job done, but I don't think this can be stressed enough.
I noticed in the comments you asked the question:
Does this make sense, or is there a better way to do it?
There's a good chance there is a better way to do it, but without knowing more about your XML and what your users need, it's difficult to say. You said an example selection might be $xml->deals->deal[0]
. Do users just need to be able select the index of that deal? E.g., could you just let them choose from a dropdown which deal to select? Then you could just store the integer they want, and accessing that data would be much safer and simpler, to boot.
If they need more control than that, maybe you could give them a few dropdowns to help them build the "path" to the needed element. For example:
[ Element 1 (v)] [ Element 2 (v)] [ Field (v)]
| Deals | | Deal | | 0 |
| Steals | | Steal | | 1 |
| Wheels | | Wheel | |_________|
|_____________| |_____________|
Then in your code
$array_of_valid_element1 = array ('Deals', 'Steals', 'Wheels');
if(
in_array($_POST['element1'], $array_of_valid_element1)
&&
in_array($_POST['element2'], $array_of_valid_element2)
&&
in_array($_POST['element3'], $array_of_valid_element3)
)
{
echo $xml->$_POST['element1']->$_POST['element2'][$_POST['element3'];
}
You can see where the extra validation comes in! By checking against each element, you make sure the user is only doing things they're explicitly allowed to do.
I hope this gives you some ideas or helps you reconsider whether you're taking the best approach. Feel free to ask another question if you'd like more input on this. It's not simple, but that's what makes it fun!