使用前缀在codeigniter中写入文件

时间:2016-02-24 06:32:26

标签: php codeigniter

我知道这有点非常简单并有很多答案,但我没有得到我的ans所以张贴这个:

我想创建一个文件并将数据写入该文件。

我试过这个:

$data = array
        (
            'SipUserName' =>'',
            'SipAuthName' =>'' ,
            'DisplayName' =>'' ,
            'Password' => '',
            'Domain' => '', 
            'Proxy' => '', 
            'Port' => '', 
            'ServerMode' => ''

        );


        $file =  fopen('./uploads/text.ini','w');

        // Open the file to get existing content
        $current = file_get_contents('./uploads/text.ini');
        // Append a new person to the file
        $current .= implode('', $data);
        // Write the contents back to the file
        file_put_contents('./uploads/text.ini', $current);

第二个选项

        $this->load->helper('file');
        $data = array
        (
            'SipUserName' =>'',
            'SipAuthName' =>'' ,
            'DisplayName' =>'' ,
            'Password' => '',
            'Domain' => '', 
            'Proxy' => '', 
            'Port' => '', 
            'ServerMode' => ''

        );


        $fp = fopen('./uploads/test.ini', 'w');
        fwrite($fp, implode("", $data));

        fclose($fp);

预期输出

[INIDetails]

    SipUserName =
    SipAuthName =
    DisplayName = 
    Password = 
    Domain = 
    Proxy = 
    Port = 
    ServerMode=Automatic

但是不起作用。

我想把这个数组写成sting到我的文件。

另外,我想为每个新文件设置一个前缀,我创建该怎么做?

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

$data = array(
    'SipUserName' => '',
    'SipAuthName' => '',
    'DisplayName' => '',
    'Password'    => '',
    'Domain'      => '',
    'Proxy'       => '',
    'Port'        => '',
    'ServerMode'  => '');

$file = fopen('uploads/text.ini', 'a+');

$str = implode('', $data);

fwrite($file, "$str\n");
fclose($file);

或者您可以尝试下面,因为这是一个ini文件:

$data = array(
    'SipUserName' => '',
    'SipAuthName' => '',
    'DisplayName' => '',
    'Password'    => '',
    'Domain'      => '',
    'Proxy'       => '',
    'Port'        => '',
    'ServerMode'  => '');

$file = fopen('uploads/text.ini', 'a+'); // notice that we use a+ mode. See documentation for clear explanation about writing mode

fwrite($file, "[INIDetails]\n");

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

fclose($file);

第二个代码将写入文件:

[INIDetails]
    SipUserName = 
    SipAuthName = 
    DisplayName = 
    Password = 
    Domain = 
    Proxy = 
    Port = 
    ServerMode = 

您应该详细了解implodefopen的语法,以便了解它们的工作原理。