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
Go to File > Preferences > Settings, search for settings.json in the search field, then click the Edit in settings.json link.
You can choose to add the setting at a User or Workspace level.
Add a comma after the last line and then add the following code on the next line:
Save the file.
- 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
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.
Click on LF at the top.
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 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!