-1

I know this is kind of very simple and has many answers but i didn't got my ans so posting this:

I want to create a file and write data to that file.

I have tried this :

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

2nd Option

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

expected output

[INIDetails]

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

But doesn't work.

I want to write this array as sting to my file.

Also i want to set a prefix to each new file that i create how do i do this?

Rajan
  • 2,427
  • 10
  • 51
  • 111

1 Answers1

1

Try below code:

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

Or you may try below since this is an ini file:

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

2nd code will write in file:

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

You should read more about the syntax of implode and fopen so you will know how they works.

Ceeee
  • 1,392
  • 2
  • 15
  • 32