#VSCode

VS Code Fix for "End of line character is invalid" PHPCS Error

by Radu

As I’m continuing with my PHP practice, I decided to install some additional extensions for Visual Studio Code.

One of those extensions is PHP CodeSniffer (PHPCS), which is awesome!

I set it to the PSR-2 standard and started to adjust the code, but I couldn’t figure out the solution to one of the errors:

End of line character is invalid; expected "\n" but found "\r\n"

Fortunately, after some digging around, I found the solution, and I’ll share with you in this tutorial!

What’s Causing This PHPCS Error?

From what I understand, the error is related to the operating system and the newline control codes: LF (Line Feed) and CR (Carriage Return).

Some operating systems, such as Windows, use CRLF (or CR+LF), while others, such as Linux, use LF.

So, if you’re using Windows, Visual Studio Code will set the code to CRLF by default, and, apparently, PHP CodeSniffer wants it set to LF to stop “screaming”.

You can read more about these codes here.

Fix “End of line character is invalid; expected ‘\n’ but found ‘\r\n’” Error in VS Code

I’ll show you how to set LF in VS Code per file or as default for all new files.

Set LF as default

Step 1

Go to File > Preferences > Settings, search for settings.json in the search field, then click the Edit in settings.json link.

edit settings.json vs code

You can choose to add the setting at a User or Workspace level.

Step 2

Add a comma after the last line and then add the following code on the next line:

"files.eol": "\n"

Save the file.

Notes

  • This won’t apply for the existing files that are already set to CRLF. It will apply for the newly created files.
  • You might need to restart VS Code after the edit, as Biggs pointed out in the comments.

Check the second method to see how to change CRLF to LF on every file.

Set LF manually, per file

Step 1

Click on the CRLF button found at the bottom-right in VS Code.

Alternatively, you can open your Command Palette by pressing CTRL+SHIFT+P, add Change End of Line Sequence, then select LF, as you see in the second step.

Step 2

Click on LF at the top.

That’s it!

Now, the “End of line character is invalid; expected ‘\n’ but found ‘\r\n’” CodeSniffer error should disappear, and the new files you create should be set to LF automatically (if you set it as default).

That’s a Wrap

I hope you found this guide useful and the fix worked for you.

If some info is outdated or incorrect, or you have anything to add, say or ask, please contact me via Twitter or email.

About Radu

I've been working online, from home, for over 9 years. I learned a lot of different stuff related to websites. My main expertise was WordPress, but for some time, we parted ways, and I started focusing more on web development.