webman用tp模板引擎写的网站怎么压缩html渲染输出

晚安。

截图
压缩成这样类似的

458 1 0
1个回答

北月

写个函数格式化一下即可:

/**
 * @param string $html
 * @return string
 */
function minify_html(string $html): string
{
    $html = str_replace(PHP_EOL,'',$html);
    $html = str_replace("
",'',$html);
    return preg_replace(
        [
            '/\>[^\S ]+/s',  // 删除标签后面空格
            '/[^\S ]+\</s',  // 删除标签前面的空格
            '/(\s)+/s'       // 将多个空格合并成一个
        ],
        [
            '>',
            '<',
            '\\1'
        ],
        $html
    );
}

中间件:

<?php
namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use function minify_html;

class MinifyHtml implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        /** @var Response $response */
        $response = $handler($request);
        $content_type = (string)$response->getHeader('Content-Type');
        if ($content_type === 'text/html' || $content_type === '') {
            $response->withBody(minify_html($response->rawBody()));
        }
        return $response;
    }
}
  • 北月 2023-08-21

    另外:如果你的HTML代码中存在JS代码块,JS语句前后又没有加分号,那是会出问题的,这是JS的问题

  • 晚安。 2023-08-22

    确实可以,js后面好像加了分号的也会有出问题的

  • 北月 2023-08-22

    这是你JS代码的问题,可以自己手工去掉JS代码的空格,然后看看是不是一样报错。

🔝