doudiza9154 2016-02-29 06:38
浏览 68
已采纳

如何在PHP中解析ini文件时写入数组名?

I am using parse_ini_file to parse an ini file using PHP.

Now I first upload an INI file to my server then open it and allow user to mak custom changes to the file.

Now once users has edited the file i get the data from post and save the file back to server. But Now i dont get my sections. INIdetails,Dialplan in the updated file so when i also want to write that to file how to do that?

This is the code :

$this->data['parameters'] = parse_ini_file($path.$filename,true);

    /*Getting Our POST DATA from View*/
        $data = array(
                        'SipUserName' => $this->input->post('SipUserName') , 
                        'SipAuthName' => $this->input->post('SipAuthName'), 
                        'DisplayName' => $this->input->post('DisplayName'),
                        'Password' => $this->input->post('Password'), 
                        'Domain' => $this->input->post('Domain'), 
                        'Proxy' => $this->input->post('Proxy'),
                        'Port' => $this->input->post('Port'), 
                        'ServerMode' => $this->input->post('ServerMode'),
                        'Param_1' => $this->input->post('Param_1'),
                        'Param_2' => $this->input->post('Param_2')
                    );


        /*Creating New file with the name of customer loggedin*/


        $name = $this->session->userdata('username');
        $ext = $this->session->userdata('extension');       
        $custom_file = fopen('uploads/'.$name.'_'.$ext.'.ini', 'w');




        fwrite($custom_file, "[INIDetails]
");

        foreach ($data as $key => $value) 
        {
            fwrite($custom_file, "    $key = $value
");
        }



        fclose($custom_file);   

        /*Setting path to New CUSTOM file with customer name as prefix*/
        $file = $path.$custom_file;


        function write_php_ini($array, $file)
        {
            $res = array();
            foreach($array as $key => $val)
            {
                if(is_array($val))
                {
                    $res[] = "[$key]";
                    foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
                }
                else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
            }
            safefilerewrite($file, implode("
", $res));
        }

        function safefilerewrite($fileName, $dataToSave)
        {    if ($fp = fopen($fileName, 'w'))
            {
                $startTime = microtime(TRUE);
                do
                {            $canWrite = flock($fp, LOCK_EX);
                   // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
                   if(!$canWrite) usleep(round(rand(0, 100)*1000));
                } while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));

                //file was locked so now we can store information
                if ($canWrite)
                {            fwrite($fp, $dataToSave);
                    flock($fp, LOCK_UN);
                }
                fclose($fp);
            }

        }

        /*Creates ini file, dumps array to string and creates .INI file*/
        write_php_ini($data,$file);
  • 写回答

2条回答 默认 最新

  • dsrbb20862 2016-03-02 02:58
    关注

    The culprit from your previous code is that your array is not formatted correctly, it should be array of arrays to achieve what you want.

    Try below code:

    // First read the ini file that the user was editing
    // Your idea to read the existing ini file is good, since it will generate you the structured array
    $previous_data = parse_ini_file($path . $filename, true);
    
    // Overwrite/edit the previous_data using user's post data
    $previous_data['INIDetails']['SipUserName'] = $this->input->post('SipUserName');
    $previous_data['INIDetails']['Password']    = $this->input->post('Password');
    $previous_data['INIDetails']['Domain']      = $this->input->post('Domain');
    $previous_data['INIDetails']['Proxy']       = $this->input->post('Proxy');
    $previous_data['INIDetails']['Port']        = $this->input->post('Port');
    $previous_data['INIDetails']['SipAuthName'] = $this->input->post('SipAuthName');
    $previous_data['INIDetails']['DisplayName'] = $this->input->post('DisplayName');
    $previous_data['INIDetails']['ServerMode']  = $this->input->post('ServerMode');
    $previous_data['INIDetails']['UCServer']    = $this->input->post('UCServer');
    $previous_data['INIDetails']['UCUserName']  = $this->input->post('UCUserName');
    $previous_data['INIDetails']['UCPassword']  = $this->input->post('UCPassword');
    
    $previous_data['DialPlan']['DP_Exception'] = $this->input->post('DP_Exception');
    $previous_data['DialPlan']['DP_Rule1']     = $this->input->post('DP_Rule1');
    $previous_data['DialPlan']['DP_Rule2']     = $this->input->post('DP_Rule2');
    
    $previous_data['DialPlan']['OperationMode']   = $this->input->post('OperationMode');
    $previous_data['DialPlan']['MutePkey']        = $this->input->post('MutePkey');
    $previous_data['DialPlan']['Codec']           = $this->input->post('Codec');
    $previous_data['DialPlan']['PTime']           = $this->input->post('PTime');
    $previous_data['DialPlan']['AudioMode']       = $this->input->post('AudioMode');
    $previous_data['DialPlan']['SoftwareAEC']     = $this->input->post('SoftwareAEC');
    $previous_data['DialPlan']['EchoTailLength']  = $this->input->post('EchoTailLength');
    $previous_data['DialPlan']['PlaybackBuffer']  = $this->input->post('PlaybackBuffer');
    $previous_data['DialPlan']['CaptureBuffer']   = $this->input->post('CaptureBuffer');
    $previous_data['DialPlan']['JBPrefetchDelay'] = $this->input->post('JBPrefetchDelay');
    $previous_data['DialPlan']['JBMaxDelay']      = $this->input->post('JBMaxDelay');
    $previous_data['DialPlan']['SipToS']          = $this->input->post('SipToS');
    $previous_data['DialPlan']['RTPToS']          = $this->input->post('RTPToS');
    $previous_data['DialPlan']['LogLevel']        = $this->input->post('LogLevel');
    
    // Set Name of New file with the name of customer logged in
    $name        = $this->session->userdata('username');
    $ext         = $this->session->userdata('extension');
    $custom_file = "$name_$ext.ini";
    $new_filename        = $path . $custom_file;
    
    // Write the INI file
    write_php_ini($data, $new_filename);
    
    function write_php_ini($array, $new_filename)
    {
        $res = array();
        foreach ($array as $key => $val) {
            if (is_array($val)) {
                $res[] = "[$key]";
                foreach ($val as $skey => $sval) {
                    $res[] = "$skey = " . (is_numeric($sval) ? $sval : '"' . $sval . '"');
                }
    
            } else {
                $res[] = "$key = " . (is_numeric($val) ? $val : '"' . $val . '"');
            }
    
        }
        safefilerewrite($new_filename, implode("
    ", $res));
    }
    
    function safefilerewrite($new_filename, $dataToSave)
    {
        if ($fp = fopen($new_filename, 'w')) {
            $startTime = microtime(true);
            do {
                $canWrite = flock($fp, LOCK_EX);
                // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
                if (!$canWrite) {
                    usleep(round(rand(0, 100) * 1000));
                }
    
            } while ((!$canWrite) and ((microtime(true) - $startTime) < 5));
    
            //file was locked so now we can store information
            if ($canWrite) {
                fwrite($fp, $dataToSave);
                flock($fp, LOCK_UN);
            }
            fclose($fp);
        }
    }
    

    From your previous code, there are bunch of inappropriate codes which I remove. Also, too many inconsistencies like Method naming, variable naming etc.

    If your function was named Camel cased then through out your code it must be named as camel-cased. If your variables are with underscore, then through out your code, they must have underscore for two or more worded variable.

    I didn't edit the naming convention of your code so you won't be confused but i suggest to have a consistent naming convention through out your project.

    UPDATED:

    based on your answer, it seems like you changed your whole code. I would like to provide another way using nested foreach and passing by reference that save couple of lines:

    $this->data['params'] = $this->parameter_m->get();
    
    $this->data['parameters'] = parse_ini_file($path . $filename, true);
    
    foreach ($this->data['parameters'] as $key_header => &$value_header) {
        foreach ($value_header as $key_item => &$value_item) {
            $value_item = $this->input->post($key_item);
        }
    }
    
    $this->load->helper('file');
    
    $this->load->library('ini');
    
    $file = $path . $filename;
    
    $ini = new INI($file);
    $ini->read($file);
    $ini->write($file, $this->data['parameters']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料