I am trying to write a multiline string into a text file but it does not appear as multi-line text. Here's my code

$hostname = "localhost";
$username = "root";
$password = "sample";
$dbname = "code";

$code = <<< THECODE

    ; This is the main configuration file for your web app
    ; The web administrator shall set the correct settings to initialise the app

    [dbconfig]
    hostname = $hostname
    username = $username
    password = $password
    databasename = $dbname
    THECODE;
    $fp = @fopen('config.ini','w') or die_message("Could not write configuration file</br>Change your folder permissions using <b>chmod 777</b>");
    fwrite($fp, $code);
    fclose($fp);

But when I open the written file it shows everything in a single line! Like

; This is the main configuration file for your web app;The web administrator shall set the correct settings to initialise the app[dbconfig]hostname = $hostnameusername = $usernamepassword = $passworddatabasename = $dbname

In currently running on Windows, I never had this problem on the Mac i.e. Unix based machines. I'm guessing it has something to do with the CRLF in Windows. Is there a way to tell PHP to handle this on its own without having to write a PHP_EOL at the end of each line?

SOLVED IT
Found a piece of code to normalize the string to whatever platform I am currently working on

define('CR', "\r");          // Carriage Return: Mac
define('LF', "\n");          // Line Feed: Unix
define('CRLF', "\r\n");      // Carriage Return and Line Feed: Windows
define('BR', '<br />' . PHP_EOF); // HTML Break

function normalize($s) {
    // Normalize line endings using Global
    // Convert all line-endings to current platform's format
    $s = str_replace(LF, PHP_EOL, $s);
    $s = str_replace(CR, PHP_EOL, $s);
    $s = str_replace(CRLF, PHP_EOL, $s);
    // Don't allow out-of-control blank lines
    $s = preg_replace("/n{2,}/", PHP_EOL . PHP_EOL, $s);
    return $s;
}

A note about PHP_EOL, it sets the line endings to what is correct for the current server, not necessarily the client computer. Meaning if you're on a windows computer and you view a file with PHP_EOL line endings generated from a Linux server, it'll all be on the same line.

EDIT: As you found a code that works during time I was writing this, I edited my post to only include the EOL note. Good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.