【问题标题】:How write arrays name while parsing an ini file in PHP?在 PHP 中解析 ini 文件时如何写入数组名称?
【发布时间】:2016-02-29 06:38:40
【问题描述】:

我正在使用parse_ini_file 使用 PHP 解析一个 ini 文件。

现在我首先将一个 INI 文件上传到我的服务器,然后打开它并允许用户对文件进行自定义更改。

现在,一旦用户编辑了文件,我就会从帖子中获取数据并将文件保存回服务器。但现在我没有得到我的部分。 INIdetails,Dialplan在更新的文件中所以当我也想把那个写到文件中怎么办?

这是代码:

$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]\n");

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



        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("\r\n", $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);

【问题讨论】:

  • 为什么要使用parse_ini_file 写入ini文件?这是没有意义的。 parse_ini_file 的目的是让你可以从代码中读取ini文件中的结构化数据。不是相反。
  • 下面函数写入ini文件]
  • 我对你的函数做了什么并不感到困惑。我的问题是为什么要使用parse_ini_file 写入ini 文件?。这不是parse_ini_file 的用途。它用于读取 ini 文件中的值 您的代码,而不是写入 值到ini 文件中。
  • 我没有使用 parse_ini_file 来编写 ini 文件。我有一个写入 .ini 文件的函数 write_php_ini
  • 那你为什么要使用parse_ini_file呢?您的问题令人困惑,因为您在此处拥有的函数将数组作为输入,这没有任何意义。为什么用户上传 ini 文件作为输入,而您正在编写一个函数,该函数将数组作为输入写入 ini 文件?

标签: php codeigniter associative-array


【解决方案1】:

你之前代码的罪魁祸首是你的数组格式不正确,它应该是数组数组来实现你想要的。

试试下面的代码:

// 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("\r\n", $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);
    }
}

从您之前的代码中,我删除了一堆不合适的代码。另外,方法命名、变量命名等不一致的地方太多了。

如果你的函数被命名为骆驼大小写,那么在整个代码中它必须被命名为骆驼大小写。如果您的变量带有下划线,那么在整个代码中,它们必须带有下划线来表示两个或多个单词的变量。

我没有编辑您代码的命名约定,因此您不会感到困惑,但我建议您在整个项目中使用一致的命名约定。

更新:

根据您的回答,您似乎更改了整个代码。我想提供另一种使用嵌套 foreach 并通过引用传递的方法,以节省几行:

$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']);

【讨论】:

【解决方案2】:

我终于得到了答案:

我将遍历从 POST 获得的内容,并获取每个数组的密钥。然后我会将结果提供给我的 Write Method

$this->data['params'] = $this->parameter_m->get();

        /*Getting the parameters to display on view*/

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




        while (current($this->data['parameters']) ) 
        {
            $param_set = current($this->data['parameters']);
            $param_type = key($this->data['parameters']);

                foreach ($param_set as $key =>$value) 
                {

                    $this->data['parameters'][$param_type][$key] = $this->input->post($key);

                } 

                next($this->data['parameters']);
        }




        $this->load->helper('file');

        $this->load->library('ini');

        $file = $path.$filename;

        $ini = new INI($file);
        $ini->read($file);
        $ini->write($file, $this->data['parameters']);  

【讨论】:

  • 似乎这与你问题中的代码完全不同,但我更新了我的答案,以防你想要另一种方法来实现这一点:) 祝你好运朋友
  • @Ceeee 你的代码是正确的,但我只是不想为我得到的每个 POST 值写,所以我只是使用循环,非常感谢你的帮助
  • 不用担心。随时为您提供帮助 :) 您现在的代码比以前的代码更好。您对动态循环遍历项目而不是逐个编辑它们是正确的:)
  • @Ceeee 请帮我解决这个问题:stackoverflow.com/questions/36052603/…
猜你喜欢
  • 2014-08-12
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
  • 2013-04-26
  • 2015-10-13
  • 1970-01-01
  • 2021-09-18
相关资源
最近更新 更多