如何通过php将变量分配给地址

I wana to assign a variable such as 'heloo' to an address such as ->system_settings->settings->hostname and i write a function for.now when i write that address manually this function work correctly and assign 'hello' to that address,but,when i wana to gave address dynamically it doesn't work. my function :

<?php
write_xml("->system_settings->settings->hostname",'Helloooooooo');
function write_xml($tag_address,$value) {

    $xml = simplexml_load_file("test.xml")
                 or die("Error: Cannot create object");
    //  $xml->system_settings->settings->hostname = $value;
    $xml->$tag_address=$value;
    $xml->asXML("test.xml");

}
?>

when i run the command line it works but in dynamical mode it doesn't work and identifies $tag_address in this line $xml->$tag_address=$value; as a string,not as an address. what should i do? TNX

The solution is not that easy.

The easiest, but least secure, is to use eval() function so you can write something like this:

eval('$xml'.$tag_address.' = $value;'); // note ' as quotation marks

The most correct way can be that you split your text and create a chained object manually. You can't just refer to all chained elements in one string, but you can do this step-by-step with one element.

For example something like

$splitted_text = explode('->', $tag_address);
$node = $xml;
foreach($splitted_text as $object)
  $node = &$node -> {$object};
// at the moment $node = $xml->system_settings->settings->hostname
$node = $value;
$xml->asXML("test.xml");

should work. I haven't tested it, but the idea is that in each iteration you prepare $node variable going deeper into the $xml variable. At the end you modify only the $node, but as objects are only references, so $xml should change accordingly.

This example assumes that there is no -> in the beginning of $tag_address. If it is, there would be a problem with explode() function because this would create empty string as the first element of the $splitted_text array.

So you might need to remove this empty element or apply calling as

 write_xml("system_settings->settings->hostname",'Helloooooooo');

without the first ->.

Use XPath to select the node, then update the value. For that, you need the proper systax for your tag address.

write_xml("system_settings/settings/hostname", 'Helloooooooo');

function write_xml($tag_address, $value)
{
    $xml         = simplexml_load_file('test.xml') or die("Error: Cannot create object");
    $nodes       = $xml->xpath($tag_address);
    $nodes[0][0] = $value;
    $xml->asXML('test.xml');
}