When we use fwrite to write files, novices will encounter one of the most common problems that must be solved, and that is newline writing.
We all know the line break character of PHP: n and carriage return character: r. When a line break is needed, the combination "rn" is usually used. But why does n newline character not work when we use fwrite to write a file? Let’s look at the following example first:
<?php $filename = 'file.txt'; $word = '你好!\r\n欢迎来到www.webkaka.com'; $fh = fopen($filename, "a"); //w从开头写入 a追加写入 echo fwrite($fh, $word); fclose($fh); ?>
The carriage return and line feed character "rn" is added to the string of $word, but the output result is not as expected. The carriage return and line feed character "rn" is not included. is parsed as a newline character, but is directly output as a character.
Why does this happen? After research, it turns out that the single and double quotes are causing the trouble! We just replace the single quotes "'" in the $word definition string with double quotes """. The correct way to write it is as follows :
$filename = 'file.txt'; $word = "你好!\r\n欢迎来到www.webkaka.com"; $fh = fopen($filename, "a"); //w从开头写入 a追加写入 echo fwrite($fh, $word); fclose($fh);
In the above example, echo fwrite() displays a number, which represents the length of the string.
Knowledge expansion
Use double quotes (") to define the string , PHP understands more escape sequences for special characters:
Transfer sequence description
nLine feed
rCarriage return
tHorizontal tab character
[/td>Backslash
$Dollar sign
" Double quotes
[0-7]{1,3} This regular expression sequence matches a character represented in octal notation
x[0-9A-Fa-f]{1,2} This regular expression sequence matches A character represented in hexadecimal notation