Format code command for PHP/HTML in Visual Studio Code
Update 2021-07-21
It's been more than half a decade since I first wrote this answer. The extensions to which I originally linked are abandoned, and Visual Studio Code's intrinsic PHP support hasn't improved, which is disappointing. The only decent extension still standing of which I'm aware is PHP Intelephense, which uses a freemium model: basic features are free, and a lifetime license is $12 USD as of writing.
The free version of Intelephense supports code formatting with the usual shortcuts (Alt + Shift + F on Windows and Linux, ⌥⇧F on macOS). Visual Studio Code continues to lack built-in support for PHP code formatting and will direct you to the extension marketplace if you attempt to format PHP without an appropriate extension installed.
Original answer
Visual Studio Code has pretty awesome PHP support. What it lacks is covered by extensions. A quick search reveals at least three (1, 2, and 3) that claim to support PHP formatting.
They mostly seem to use the standard shortcut of Alt + Shift + F on Windows/Linux, with varying shortcuts on Mac. If you're on Mac, give ⌥⇧F a try.
For the best format setting for mixed PHP, HTML, and JavaScript code, just use 'PHP CS FIXER'.
And then use this simple configuration on your setting.json
file:
"php-cs-fixer.executablePath": "${extensionPath}\\php-cs-fixer.phar",
"[php]": {
"editor.defaultFormatter": "junstyle.php-cs-fixer",
"editor.formatOnSave": true
},
"php-cs-fixer.rules": "@PSR2",
"php-cs-fixer.formatHtml": true,
The problem with most of the solutions is that they all are registered as formatting providers and within Visual Studio Code you can only run one formatter on a save for a specific file type.
So one may get you all the HTML, CSS, JavaScript code, but leave out the PHP code. Or if you use a regular PHP formatter there isn't one that exists that does the HTML correctly.
I went ahead and made an extension that runs before the save hook and isn't registered as a PHP formatter, so it will do all the HTML with js-beautify and then you can use something like PHPCS + PHPCBF to format the HTML. So it's basically, as far as I'm concerned, the best solution currently available.
Format HTML in PHP on the Visual Studio Code marketplace.