


PHP compression HTML function easily compresses html/js/Css and precautions_PHP tutorial
The reason for compressing HTML
How to improve the loading speed of web pages and how to optimize HTML pages are questions that every webmaster who wants to improve their website building skills has thought about. In fact, there are still many ways to optimize web pages.
Some children asked Higrid how to compress HTML, that is to say, whether it can compress all HTML, js, and CSS into one line before running, and remove comment marks, line breaks, spaces, tabs, etc. A direct benefit of this is to reduce the size of the HTML page and improve the front-end loading speed. Many people think that gzip is enabled, but generally it is rare to enable gzip compression for html, because the current html is dynamic and does not use the browser cache. If gzip is enabled, each request needs to be compressed, which will consume more servers. For resources, it is better to enable gzip for js and css because both js and css use cache. And everyone also uses a lot of software to filter compression, and there are also online js/css/html compression tools. Higrid thinks it is very troublesome and has poor readability. Higrid believes that if the compression function is made into a function, developers will see an uncompressed state, but when visitors visit, the server-side program will compress the HTML page and clear comment marks, line breaks, spaces, and tabs. Wait to achieve the purpose of reducing the size of html. If you frequently visit higrid.net, right-click to view the html source code, and you will see that the html source code of this article has been compressed. Including the free content management system provided by higrid.net, the output is compressed html, with blanks, line breaks, and tabs removed. But there are some exceptions on higrid.net, that is, higrid.net mainly recommends online tables, online graphics, including jquery demos. For the convenience of visitors, compression is not enabled.
Therefore, higrid personally feels that the biggest benefit of compressing html is to make a lot of money. As long as you write the function once, you can call it when you need to use it in the future. All programs can use it without adding any extra development work. Today higrid will share with you a few functions that I personally find useful. Please give it a try. I believe you will like it.
Using php to compress HTML
Since higrid is more interested in php, it uses php to compress HTML. Of course, other languages are also similar, such as using asp to compress HTML. The truth is It should be the same.
higrid writes the function of compressing HTML as a function in PHP. In fact, there are many such PHP compression functions on the Internet. If you don’t believe me, you can search on Baidu or Google, but most of them are not very useful, especially for compressing JS or compressing CSS. Sometimes, the main reason is that some differences in compression annotations and other aspects cause problems. Let’s look at this function first:
/**
* Compress html: clear newlines, clear tabs, remove comment marks
* @param $string
* @return compressed $string
**/
function compress_html ($string){
$string=str_replace("rn",'',$string);//Clear newline characters
$string=str_replace("n",'',$string);// Clear newlines
$string=str_replace("t",'',$string);//Clear tabs
$pattern=array(
"/> *([^ ]*) *",//Remove the comment mark
"/[s]+/",
"//",
"/ " /",
"/ "/",
"'/*[^*]**/'"
);
$replace=array (
">\1< ;",
" ",
"",
""",
""",
""
);
return preg_replace($pattern, $replace , $string);
}
Notes on using php to compress HTML
php to compress HTM. The implementation method is mainly to use regular expressions to search and replace. . When compressing HTML, you should mainly pay attention to the following points:
1. In HTML documents, multiple whitespace characters are equivalent to one whitespace character. In other words, deletion of whitespace characters such as line breaks is unsafe and may cause differences in the styles of some elements.
There is a pre in 2.html, which means preformatted text. Any blanks in it cannot be deleted, so the content format in the pre and textarea tags needs to be retained and cannot be compressed.
3. There may be IE conditional comments in HTML. These conditional comments are part of the document logic and cannot be removed. Therefore, when removing html comments, some comments cannot be removed, such as:
4. Pay attention when compressing comments in embedded js, because comment symbols may appear in the string, such as: var url = "http: //www.higrid.net"; // The previous // is not a comment
5. For dynamic pages, HTML compression may also increase the CPU load of the server, which is not worth the gain
PHP compressed html function code used by higrid
Since comments have an effect on the code, the php compressed html function code used by higrid does not remove the comments and goes directly to the code.
function higrid_compress_html($higrid_uncompress_html_source )
{
$chunks = preg_split( '/(
php compression html function code summary
some Compressing HTML is not recommended for children's shoes. The main reason is that in addition to the above-mentioned precautions for compressing HTML with PHP, good results can be achieved through gzip compression. In addition, because there are too many roles that affect HTML (static, dynamic, front-end dynamic), and there are no quantitative indicators, it is difficult to control how it is compressed (to what extent the code is written). The code needs to consider execution efficiency rather than transmission efficiency. For dynamic pages, HTML compression may also increase the CPU load of the server, which is not worth the gain. Google compressed web pages because in the early days, it wanted to keep the homepage text within one or two packages as much as possible, and its homepage was too important and the traffic was outrageous. Compressing one byte, the total traffic is a large number, so it is naturally necessary. Further compression is problematic, and compression of HTML is not recommended unless thoroughly tested like Google (which also only compresses a small number of core service pages).
But using higrid.net’s php compression html function code can solve this problem very well. Okay, let’s try it soon.

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor
