How can I format PHP files with HTML markup in Visual Studio Code?

The extension Beautify (from HookyQR) just does it very well. Either add PHP, and any other file extension type, to the configuration. As said by Nico, here is an example:

  1. Go to user settings (Ctrl + Shift + PUser settings (UI) or Ctrl + , (comma)

  2. Search for Beautify in the field above. And click on "Edit in settings.json" for "Beautify: Config".

  3. For the "html" section, add "php" and "blade".

    Enter image description here Enter image description here

###Usage

You can invoke it directly. Press F1, and then write Beautify. The auto completion gives you two choices, "Beautify file" and "Beautify selection". Choose the one you need, and it will do the job. That's a straightforward direct way.

Enter image description here

You can also add a keybinding to have a keyboard shortcut. Here is how to do it:

  1. Open keybindings.json (go to menu FilePreferencesKeyboard Shortcuts)

  2. Click in the above. Open and edit file keybindings.json

  3. Add the following into the closed brackets, []

    {
           "key": "alt+b",
           "command": "HookyQR.beautify",
           "when": "editorFocus"
    }
    

    Choose any key you want, and make sure you don't override an existing one. Search first in the left side if it exists or not.

    Enter image description here

Note that all of those things are well documented in the description of the extension.

Extra: Note about blade

(suite to @Peter Mortensen clarification pinpoint)

blade or blade.php

If you are confused if it's blade or blade.php for the setting! I'll clear it up for you! It's blade! That's vscode keyword for the language!

How do you know ?

First if you open the list of languages as by the image bellow:

enter image description here

Write blade

enter image description here

You can see Laravel Blade (blade)! The language keyword is in the paratheses! blade!

Well but how to check!

Try with blade.php in the settings!

enter image description here

Try to beautify

enter image description here

You'll get an asking context menu for what language (html, css, js)!

enter image description here

So it doesn't works!

To really know ! Put back blade! And it will work and beautify directly!

How well it works with blade

The awesome answer to that! Is try it, and see for yourself!

But if you ask me! I'll say it does work as with html! It can be too handy! And you may need to fix some lines! Depending on your expectations and your style!

Here an illustration! I screwed the indentation in purpose

enter image description here

And here the beautification result:

enter image description here


Beautify (from HookyQR) does solve this problem!

Many people add "blade.php" and "php" to the HTML configuration. Beautify does not recognize and manually choose an HTML template. Instead, just adding "blade" to the HTML configuration fixes all issues.