#51: Creating and Writing to a File

Here's how to write a string to a file:

<?
$file_data = "Hello, file.\nSecond line.";
$fd = fopen('file.txt', 'w');
if (!$fd) {
   echo "Error! Couldn't open/create the file.";
   die;
}
fwrite($fd, $file_data);
fclose($fd);
?>

Notice that this script explicitly includes newlines. When viewed on a Unix machine, the file looks like this:

Hello, file.
Second line.

The separator between the two lines is called a newline. On Unix and Macs, it's a single character represented in PHP as \n inside double quotes. However, in Windows and Macs, the newline is the \r\n sequence ("carriage return, then newline").

Therefore, if you actually care about cross-platform text file readability, you need to be a little careful. A Unix text ...

Get Wicked Cool PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.