Search code examples
phpfwritefile-writing

How to put new line in php file fwrite


I am writing a file that is plan.php. It is a php file that I am writing. I am using \n to put the new line in that file but it is giving me save output.

Here is code:

$datetime = 'Monthly';
$expiry = '2017-08-07';
$expiryin = str_replace('ly', '',$datetime);
if($expiryin == 'Month' || $expiryin == 'Year') {
    $time = '+ 1'.$expiryin.'s';
} else {
    $time = '+'.$expiryin.'s';
}
   $expiry_date = date('Y-m-d', strtotime($time, strtotime($expiry)));

$string = createConfigString($expiry_date);

$file = 'plan.php';
$handle = fopen($file, 'w') or die('Cannot open file:  '.$file);
fwrite($handle, $string);

And the function is:

function createConfigString($dates){
    global $globalval;

    $str = '<?php \n\n';
    $configarray = array('cust_code','Auto_Renew','admin_name');
    foreach($configarray as $val){
            $str .= '$data["'.$val.'"] = "'.$globalval[$val].'"; \n';
    }
    $str .= '\n';
    return $str;
}

But it is giving the output like:

<?php   .......something....\n.....\n

So my question is how to put the new line in this file.

Note: There is no error in code. I have minimized the code to put here.


Solution

  • As everyone already mentioned '\n' is just a two symbols string \n.

    You either need a "\n" or php core constant PHP_EOL:

    function createConfigString($dates){
        global $globalval;
    
        // change here
        $str = '<?php ' . PHP_EOL . PHP_EOL;
        $configarray = array('cust_code','Auto_Renew','admin_name');
        foreach($configarray as $val){
            // change here 
            $str .= '$data["'.$val.'"] = "'.$globalval[$val].'";' . PHP_EOL;
        }
        // change here
        $str .= PHP_EOL;
        return $str;
    }
    

    More info about interpreting special characters in strings http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double