Highlight PHP in an HTML File in Visual Studio Code

To highlight PHP code in an HTML file in Visual Studio Code (VS Code), switch the editor’s language mode to PHP. Change it in the status bar for one file, or add a files.associations entry if you regularly edit the same template in a project.

Change the current file’s language mode

Open the .html file. Select HTML in the bottom-right status bar or run Change Language Mode from the Command Palette, then pick PHP. Check that the status bar says PHP and that code between <?php ... ?> is highlighted. The filename extension stays the same.

PHP support in VS Code

Save a file association in the workspace

Open the project folder and run Preferences: Open Workspace Settings (JSON) from the Command Palette. For a single-folder project this edits .vscode/settings.json. The example targets only legacy-template.html. Add the entry to an existing files.associations object if present. In the Settings editor, select Workspace, find Files: Associations, and use Add Item to enter the same key and value.

{
  "files.associations": {
    "legacy-template.html": "php"
  }
}

The key *.html matches every HTML file in that scope. Use the filename if the workspace also contains ordinary HTML. For a new PHP template, saving it with a .php extension is simpler when that matches the server’s configuration.

Language identifiers and file associations

User and workspace settings

Check highlighting and run the PHP example

Put this sample in legacy-template.html to check the status bar and highlighting of echo. To test execution, save the same code as demo.php and run php demo.php in that folder. With the PHP command-line runtime installed, the command prints <p>5</p>. In a browser, PHP runs when the web server passes the file to PHP. The editor’s language mode does not affect that configuration.

<p><?php echo 2 + 3; ?></p>

PHP opening and closing tags

Undo the change or troubleshoot

To undo a one-file change, select HTML in the language mode picker. To undo the association, remove the entry you added and reopen the file. If the mode still says HTML, check the filename, settings scope, and lowercase php. If it says PHP but the colors still look the same, check the opening tag and color theme.