php-cs-fixer https://github.com/PHP-CS-Fixer/PHP-CS-Fixer I do disagree on code standards being enforced in the IDE. My view is they absolutely need to be enforced at the project level to ensure consistency of code standard throughout that project. The IDE should be capable of configuring itself based on project owned configurations (this is the case when using php-cs-fixer). Edit: To your point of having an opinionated standard set out of the box. PSR12 https://www.php-fig.org/psr/psr-12/ . A rulset for this standard already exists in php-cs-fixer. Edit 2: For absolute transparency, there is also another popular capable of doing everything I mentioned above - https://github.com/squizlabs/PHP_CodeSniffer Answer from JParkinson1991 on reddit.com
🌐
CodeShack
codeshack.io › home › tools › php formatter
PHP Formatter - Beautify and Format PHP Code Online
Paste your script, upload a .php file, or start with our sample code. Choose your preferred indentation style and target PHP version, and instantly get clean, readable code formatted according to PSR standards. Consistently formatted PHP code is vital for professional development: Improved Readability: Makes complex logic, functions, classes, and mixed HTML...
🌐
Code Beautify
codebeautify.org › php-beautifier
PHP Beautifier and PHP Formatter Online
PHP Beautifier online helps to format and indent the php source code and help to share with others.
People also ask

Is this online PHP formatter free?
Yes, this tool is completely free to use online without any usage restrictions or mandatory sign-up.
🌐
codeshack.io
codeshack.io › home › tools › php formatter
PHP Formatter - Beautify and Format PHP Code Online
What does a PHP Formatter do?
A PHP Formatter analyzes your PHP script and automatically applies consistent formatting rules for indentation, spacing, line breaks, brace style, and more, based on standards like PSR-12 or Prettier's defaults. It makes messy or inconsistently styled code clean and readable without changing its logic.
🌐
codeshack.io
codeshack.io › home › tools › php formatter
PHP Formatter - Beautify and Format PHP Code Online
Why do I need to select a PHP version?
Different PHP versions introduce new syntax features (like arrow functions, null coalescing operators, typed properties). Selecting the correct version helps the formatter understand and correctly format code using features specific to that version.
🌐
codeshack.io
codeshack.io › home › tools › php formatter
PHP Formatter - Beautify and Format PHP Code Online
🌐
GitHub
github.com › mihaeu › html-formatter
GitHub - mihaeu/html-formatter: HTML Formatter is a PHP library which pretty prints HTML.
# assuming you chose to install Composer globally $ composer require mihaeu/html-formatter:* <?php require __DIR__.'/vendor/autoload.php'; echo Mihaeu\HtmlFormatter::format('<h1>Hello World</h1><p>Test</p>');
Starred by 17 users
Forked by 11 users
Languages   PHP
🌐
BeautifyTools
beautifytools.com › php-beautifier.php
Online PHP Beautifier - PHP Formatter - BeautifyTools.com
It gives the PHP code proper indentation with spaces or tabs. It also supports various indentation styles such as K&R style, Allman style, Whitesmiths style and GNU style. × · Load Cancel · × · Ok · × · Ok · × · Set Cancel · Enter php here: Results: Beautifiers And Minifiers · CSS Beautifier · CSS Minifier · HTML Beautifier ·
🌐
GitHub
github.com › lcherone › php-format-html
GitHub - lcherone/php-format-html: A simple to use HTML prettifier/formatter class written in PHP.
<?php include_once('format.php'); $html = 'Unformatted HTML string'; // initialize class $format = new Format(); // use spaces at 4 length echo $format->html($html); // use spaces at 2 length echo $format->html($html, true, 2); // use tabs echo $format->html($html, false);...
Author   lcherone
🌐
TutorialsPoint
tutorialspoint.com › online_php_formatter.htm
Online PHP Formatter | Tutorialspoint
Online PHP Formatter and Beautifier - Try online PHP Code formatter and beautifier and Editor to beautify and format PHP code using jQuery Plug-in
🌐
Reddit
reddit.com › r/phphelp › what is the most common php code formatter?
r/PHPhelp on Reddit: What is the most common PHP code formatter?
August 1, 2024 -

I found three code formatters for PHP.

  • Prettier (With PHP Plugin)

  • PrettyPHP (https://github.com/lkrms/vscode-pretty-php)

  • phpfmt (https://github.com/kokororin/vscode-phpfmt)

I was able to setup Prettier with the PHP plugin but the setup is not ideal since I have to install prettier and the prettier PHP plugin from NPM into the project every single time which is not the case when using Prettier VSCode extension with HTML, JS and CSS. I do like how Prettier has its own configuration .prettierrc files and it allows you to set a standard format for a project you are collaborating with others, however I believe formatting should be done in the IDE such as using a VSCode extension and this is the case with the Prettier extension for HTML, JS and CSS but not for PHP since it requires NPM packages.

The other two do not look popular. Am I missing something? I would like to have a standard format or be able to have an opinionated format setup like Prettier for JS but for PHP.

Find elsewhere
🌐
Visual Studio Marketplace
marketplace.visualstudio.com › items
Format HTML in PHP - Visual Studio Marketplace
Extension for Visual Studio Code - Provides formatting for the HTML code in PHP files using JSbeautify - Works well paired with a PHP formatting extension
🌐
JSON Formatter
jsonformatter.org › php-formatter
PHP Formatter and PHP Beautifier free and easy to Format PHP Code Online
This PHP Formatter online tool is very powerful. PHP stands for Hypertext Preprocessor and it's scripting language that is especially suited to web development. Danish-Canadian programmer Rasmus Lerdorf has developed PHP in 1994. PHP is Fast, flexible and pragmatic, and powers everything from blog to the most popular websites in the world. Use this icon to restore the last PHP code from the browser's local storage. ... Best and Secure online PHP Formatter work well in Windows, Mac, Linux, Chrome, Firefox, Safari, and Edge.
Top answer
1 of 3
36

you're right, there seems to be no indentation for HTML (others are also confused). XML works, even with loaded code.

<?php
function tidyHTML($buffer) {
    // load our document into a DOM object
    $dom = new DOMDocument();
    // we want nice output
    $dom->preserveWhiteSpace = false;
    $dom->loadHTML($buffer);
    $dom->formatOutput = true;
    return($dom->saveHTML());
}

// start output buffering, using our nice
// callback function to format the output.
ob_start("tidyHTML");

?>
<html>
    <head>
    <title>foo bar</title><meta name="bar" value="foo"><body><h1>bar foo</h1><p>It's like comparing apples to oranges.</p></body></html>
<?php
// this will be called implicitly, but we'll
// call it manually to illustrate the point.
ob_end_flush();
?>

result:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>foo bar</title>
<meta name="bar" value="foo">
</head>
<body>
<h1>bar foo</h1>
<p>It's like comparing apples to oranges.</p>
</body>
</html>

the same with saveXML() ...

<?xml version="1.0" standalone="yes"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
  <head>
    <title>foo bar</title>
    <meta name="bar" value="foo"/>
  </head>
  <body>
    <h1>bar foo</h1>
    <p>It's like comparing apples to oranges.</p>
  </body>
</html>

probably forgot to set preserveWhiteSpace=false before loadHTML?

disclaimer: i stole most of the demo code from tyson clugg/php manual comments. lazy me.


UPDATE: i now remember some years ago i tried the same thing and ran into the same problem. i fixed this by applying a dirty workaround (wasn't performance critical): i just somehow converted around between SimpleXML and DOM until the problem vanished. i suppose the conversion got rid of those nodes. maybe load with dom, import with simplexml_import_dom, then output the string, parse this with DOM again and then printed it pretty. as far as i remember this worked (but it was really slow).

2 of 3
4

The result:

<!DOCTYPE html>
<html>
    <head>
        <title>My website</title>
    </head>
</html>

Please consider:

function indentContent($content, $tab="\t"){
    $content = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $content); // add marker linefeeds to aid the pretty-tokeniser (adds a linefeed between all tag-end boundaries)
    $token = strtok($content, "\n"); // now indent the tags
    $result = ''; // holds formatted version as it is built
    $pad = 0; // initial indent
    $matches = array(); // returns from preg_matches()
    // scan each line and adjust indent based on opening/closing tags
    while ($token !== false && strlen($token)>0){
        $padPrev = $padPrev ?: $pad; // previous padding //Artis
        $token = trim($token);
        // test for the various tag states
        if (preg_match('/.+<\/\w[^>]*>token, $matches)){// 1. open and closing tags on same line - no change
            $indent=0;
        }elseif(preg_match('/^<\/\w/', $token, $matches)){// 2. closing tag - outdent now
            indent>0) $indent=0;
        }elseif(preg_match('/^<\w[^>]*[^\/]>.*token, $matches)){// 3. opening tag - don't pad this one, only subsequent tags (only if it isn't a void tag)
            foreach($matches as $m){
                if (preg_match('/^<(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)/im', $m)){// Void elements according to http://www.htmlandcsswebdesign.com/articles/voidel.php
                    $voidTag=true;
                    break;
                }
            }
            $indent = 1;
        }else{// 4. no indentation needed
            $indent = 0;
        }

        if ($token == "<textarea>") {
            $line = str_pad($token, strlen($token) + tab, STR_PAD_LEFT); // pad the line with the required number of leading spaces
            $result .= $line; // add to the cumulative result, with linefeed
            $token = strtok("\n"); // get the next token
            indent; // update the pad size for subsequent lines
        } elseif ($token == "</textarea>") {
            $line = $token; // pad the line with the required number of leading spaces
            $result .= $line . "\n"; // add to the cumulative result, with linefeed
            $token = strtok("\n"); // get the next token
            indent; // update the pad size for subsequent lines
        } else {
            $line = str_pad($token, strlen($token) + tab, STR_PAD_LEFT); // pad the line with the required number of leading spaces
            $result .= $line . "\n"; // add to the cumulative result, with linefeed
            $token = strtok("\n"); // get the next token
            indent; // update the pad size for subsequent lines
            if ($voidTag) {
                $voidTag = false;
                $pad--;
            }
        }
    }

    return $result;
}

// $htmldoc is your DOMDocument Object!

$niceHTMLwithTABS = indentContent($htmldoc->saveHTML(), $tab="\t");

echo $niceHTMLwithTABS;

Will result in HTML that has:

  • Indentation based on "levels"
  • Line breaks after block level elements
  • While inline and self-closing elements are not affected

The function (which is a method for class I use) is largely based on: https://stackoverflow.com/a/7840997/7646824

🌐
PHP
php.net › manual › en › tidy.examples.basic.php
PHP: Tidy example - Manual
If you're using tidy to clean up your HTML but only want your string formatted and not the whole html and head tag, you can use the following configuration array: <?php $config = [ 'indent' => true, 'output-xhtml' => false, 'show-body-only' => true ]; $tidy = new tidy; $tidy->parseString($your_html_code, $config, 'utf8'); $tidy->cleanRepair(); echo $tidy; ?>
🌐
GitHub
github.com › spyrosoft › php-format-html-output
GitHub - spyrosoft/php-format-html-output: A simple HTML pretty printer written in PHP
A simple HTML formatter. Example: <?php include_once('format.php'); $html = 'BIG STRING FULL OF HTML'; $format = new Format; $formatted_html = $format->HTML($html); echo $formatted_html;
Starred by 24 users
Forked by 30 users
Languages   PHP
🌐
Smallseotools
smallseotools.com › online-php-formatter
PHP Formatter - Beautify Your Unorganized PHP Code Online
The online PHP formatter on SmallSEOTools is based on advanced algorithms that provide you with a neat and clear version of your PHP code without letting you go through any hurdles. Our tool is just one click away from any user around the globe to use it for formatting PHP files.
🌐
Text Cleaner
textcleaner.net › home › php formatter
PHP Formatter and Beautifier to format PHP online
July 23, 2023 - If you want to format PHP? then simply paste your PHP file in the code editor and let PHP formatter format, validate and print your HTML data into pretty, human-readable format.
Top answer
1 of 14
104

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.

2 of 14
51

I installed

  • Prettier for HTML, CSS, and JavaScript files

  • PHP Intelephense for PHP files

I followed the instructions for each plugin but found I had to additionally edit settings.json manually in order to get them to work together.

"editor.defaultFormatter": "esbenp.prettier-vscode",
"[php]": {
  "editor.defaultFormatter": "bmewburn.vscode-intelephense-client"
}

The settings use Intelephense as the formatter for PHP files and use Prettier as the formatter for all other files.

Now I use Shift + Alt + F to format the files like everybody else.

🌐
Duplichecker.com
duplichecker.com › php-formatter
PHP Formatter - Beautify Your Messy PHP Code Online
Would you recommend our product/service ... contacts within your industry? ... Online PHP beautifier by Duplichecker allows you to format your unformatted PHP code in seconds. ... PHP (Hypertext Preprocessor) is a core language used widely worldwide to create web applications. The PHP file may contain HTML, JavaScript, CSS, and even AJAX, which returns the plain HTML format results after being executed on a server. However, this collection of various data languages may disturb the formatting of PHP or ...
🌐
GeeksforGeeks
geeksforgeeks.org › php-formatter
Online PHP Formatter and PHP Beautifier (Free & Easy to Use) - GeeksforGeeks
September 24, 2024 - HTML Formatter or Beautifier tools help make your HTML code clean and easy to read. They fix the spacing, line up elements properly, and highlight parts of the code, so it's easier to understand and work with.
🌐
Phpformatter
phpformatter.com
PHP Formatter – A Unique Blog about PHP
... When writing an internet address in the address bar of the browser and clicking enter to start going to that address, you send a request to the web server… ... PHP or Hypertext Preprocessor is an HTML embedded scripting language that is used to create web pages that are dynamic.