duandi1919 2013-05-27 07:32
浏览 61

如何通过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

  • 写回答

2条回答 默认 最新

  • dongmisa4779 2013-05-27 08:17
    关注

    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 ->.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端