search
HomeBackend DevelopmentPHP TutorialPHP compression HTML function easily compresses html/js/Css and precautions_PHP tutorial

PHP compression HTML function easily compresses html/js/Css and precautions_PHP tutorial

Jul 21, 2016 pm 03:13 PM
csshtmlphpfunctionaddcompressionhowaccomplishimprovePrecautionsofWeb pageeasy

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:

Copy code The code is as follows:

/**
* 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.
Copy code The code is as follows:

function higrid_compress_html($higrid_uncompress_html_source )
{
$chunks = preg_split( '/()/ms', $higrid_uncompress_html_source, -1, PREG_SPLIT_DELIM_CAPTURE ); <br>$higrid_uncompress_html_source = '';//[higrid.net] Modify compressed html: clear newlines, clear tabs, remove comment tags<br>foreach ($chunks as $c) <br>{ <br> if ( strpos( $c, '<pre class="brush:php;toolbar:false">{ <br>//[higrid.net] remove new lines & tabs <br>$c = preg_replace( '/[\n \r\t]+/', ' ', $c ); <br>// [higrid.net] remove extra whitespace <br>$c = preg_replace( '/\s{2,}/', ' ' , $c ); <br>// [higrid.net] remove inter-tag whitespace <br>$c = preg_replace( '/>\s', '>// [higrid.net] remove CSS & JS comments <br>$c = preg_replace( '/\/\*.*?\*\//i', '', $c ); <br>} <br>$higrid_uncompress_html_source .= $c; <br>} <br>return $higrid_uncompress_html_source; <br>} <br>

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326529.htmlTechArticleThe cause of compressing HTML, how to improve web page loading speed, and how to optimize html pages. I believe it is every plan to improve website building technology. The problem that the webmaster has thought about, in fact, the method of web page optimization is still very...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

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

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

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.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

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

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

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

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

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

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

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.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

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

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor