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

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"
End of line character is invalid; expected "\n" but found "\r\n" error in visual studio code

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"
fix End of line character is invalid; expected "\n" but found "\r\n" in VS Code

Save the file.

Note

This won’t apply for the existing files that are already set to CRLF. It will apply for the newly created files.

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.

CRLF button visual studio 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.

Change End of Line Sequence vs code

Step 2

Click on LF at the top.

selecting LF in vs code

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).

Related: Fix ‘Cannot Validate Since No PHP Executable Is Set’ in VS Code

That’s a Wrap

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

If you have questions or thoughts, please leave a comment or send me a message using the contact page.

Don’t forget to share the post to help out others!

2 thoughts on “VS Code Fix for “End of line character is invalid” PHPCS Error”

Leave a Comment

Tweet
Share