Home > 类库下载 > PHP类库 > body text

Why the newline character does not work when writing newline in PHP fwrite

高洛峰
Release: 2016-10-20 14:45:05
Original
1629 people have browsed it

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 = &#39;file.txt&#39;;
 $word = &#39;你好!\r\n欢迎来到www.webkaka.com&#39;;
 $fh = fopen($filename, "a"); //w从开头写入 a追加写入
 echo fwrite($fh, $word);
 fclose($fh);
?>
Copy after login

  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 = &#39;file.txt&#39;;
$word = "你好!\r\n欢迎来到www.webkaka.com";
$fh = fopen($filename, "a"); //w从开头写入 a追加写入
echo fwrite($fh, $word);
fclose($fh);
Copy after login

 

 

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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template