{"id":81,"date":"2016-03-08T00:53:35","date_gmt":"2016-03-07T19:23:35","guid":{"rendered":"http:\/\/madhurendra.com\/?p=81"},"modified":"2016-03-08T01:05:26","modified_gmt":"2016-03-07T19:35:26","slug":"website-optimization-minfiying-output-using-php","status":"publish","type":"post","link":"https:\/\/madhurendra.com\/website-optimization-minfiying-output-using-php\/","title":{"rendered":"Website Optimization – Minfiying Output using PHP"},"content":{"rendered":"

Minification is technique used in which we remove all unnecessary Whitespaces Which include tab, space, newline, carriage return etc. This is done just to reduce data transfer.
\nSince not everyone is serving a million hits a seconds – minifying html doesn’t help much, Instead enabling GZIP compression is a better technique.<\/strong><\/p>\n

Apart from this – minifying css & js help in reducing number of requests – this reduces number of http connection created to serve a client hence reducing load on server. <\/p>\n

These advantages are only a small part of web optimization process but still it is adopted widely – Why ? – Show off !, Make code unreadable, looks cool!.
\nThough server level optimizations ( like – GZIP, Cache proxy for static content, Apache vs Nginx, CDN, Server location, Number of DNS lookup, Serving content based on user device etc.) work better than just compressing code & uploading.
\nAs an example – there is latency of 400+ ms from India to NY, while 100+ ms for Singapore from India – if we have 10 request per page using singapore server will save 3sec!. <\/p>\n

I think i am diverging from main 0bj3ct!v3 of this article. Coming back to minification everyone wants their code to look cool. So recently i’ve been working on college fest site & had idea to minify the code. Did google search & finally came up with following code !<\/p>\n

Just including the below code makes the html one-liner & cool.
\nThis is just an application of output buffer<\/strong>, you can do really cool things by handling output buffer. <\/p>\n

You can read more about ob_start here<\/a>, its really interesting. <\/p>\n

Note:<\/strong> This code has methods to minify css & js – They are just for reference. I suggest using Grunt with cleancss & uglifyjs, or either. Also you should not<\/strong> use this technique in sites with heavy traffic – it will increase load on server, reduce response time. <\/em><\/p>\n

<?PHP\r\n\r\n\/\/buffer & process all the output using minify_html.\r\nob_start(\"minify_html\");\r\n\r\nfunction minify_html($input) {\r\n    if(trim($input) === \"\") return $input;\r\n    \/\/ Remove extra white-space(s) between HTML attribute(s)\r\n    $input = preg_replace_callback('#<([^\\\/\\s<>!]+)(?:\\s+([^<>]*?)\\s*|\\s*)(\\\/?)>#s', function($matches) {\r\n        return '<' . $matches[1] . preg_replace('#([^\\s=]+)(\\=([\\'\"]?)(.*?)\\3)?(\\s+|$)#s', ' $1$2', $matches[2]) . $matches[3] . '>';\r\n    }, str_replace(\"\\r\", \"\", $input));\r\n    \r\n    \/\/ Minify inline CSS declaration(s)    \r\n    if(strpos($input, ' style=') !== false) {\r\n        $input = preg_replace_callback('#<([^<]+?)\\s+style=([\\'\"])(.*?)\\2(?=[\\\/\\s>])#s', function($matches) {\r\n            return '<' . $matches[1] . ' style=' . $matches[2] . minify_css($matches[3]) . $matches[2];\r\n        }, $input);\r\n    }\r\n    return preg_replace(\r\n        array(\r\n            \/\/ t = text\r\n            \/\/ o = tag open\r\n            \/\/ c = tag close\r\n            \/\/ Keep important white-space(s) after self-closing HTML tag(s)\r\n            '#<(img|input)(>| .*?>)#s',\r\n            \/\/ Remove a line break and two or more white-space(s) between tag(s)\r\n            '#(<!--.*?-->)|(>)(?:\\n*|\\s{2,})(<)|^\\s*|\\s*$#s',\r\n            '#(<!--.*?-->)|(?<!\\>)\\s+(<\\\/.*?>)|(<[^\\\/]*?>)\\s+(?!\\<)#s', \/\/ t+c || o+t\r\n            '#(<!--.*?-->)|(<[^\\\/]*?>)\\s+(<[^\\\/]*?>)|(<\\\/.*?>)\\s+(<\\\/.*?>)#s', \/\/ o+o || c+c\r\n            '#(<!--.*?-->)|(<\\\/.*?>)\\s+(\\s)(?!\\<)|(?<!\\>)\\s+(\\s)(<[^\\\/]*?\\\/?>)|(<[^\\\/]*?\\\/?>)\\s+(\\s)(?!\\<)#s', \/\/ c+t || t+o || o+t -- separated by long white-space(s)\r\n            '#(<!--.*?-->)|(<[^\\\/]*?>)\\s+(<\\\/.*?>)#s', \/\/ empty tag\r\n            '#<(img|input)(>| .*?>)<\\\/\\1>#s', \/\/ reset previous fix\r\n            '#(&nbsp;)&nbsp;(?![<\\s])#', \/\/ clean up ...\r\n            '#(?<=\\>)(&nbsp;)(?=\\<)#', \/\/ --ibid\r\n            \/\/ Remove HTML comment(s) except IE comment(s)\r\n            '#\\s*<!--(?!\\[if\\s).*?-->\\s*|(?<!\\>)\\n+(?=\\<[^!])#s'\r\n        ),\r\n        array(\r\n            '<$1$2<\/$1>',\r\n            '$1$2$3',\r\n            '$1$2$3',\r\n            '$1$2$3$4$5',\r\n            '$1$2$3$4$5$6$7',\r\n            '$1$2$3',\r\n            '<$1$2',\r\n            '$1 ',\r\n            '$1',\r\n            \"\"\r\n        ),\r\n    $input);\r\n}\r\n\/\/ CSS Minifier => http:\/\/ideone.com\/Q5USEF + improvement(s)\r\nfunction minify_css($input) {\r\n    if(trim($input) === \"\") return $input;\r\n    return preg_replace(\r\n        array(\r\n            \/\/ Remove comment(s)\r\n            '#(\"(?:[^\"\\\\\\]++|\\\\\\.)*+\"|\\'(?:[^\\'\\\\\\\\]++|\\\\\\.)*+\\')|\\\/\\*(?!\\!)(?>.*?\\*\\\/)|^\\s*|\\s*$#s',\r\n            \/\/ Remove unused white-space(s)\r\n            '#(\"(?:[^\"\\\\\\]++|\\\\\\.)*+\"|\\'(?:[^\\'\\\\\\\\]++|\\\\\\.)*+\\'|\\\/\\*(?>.*?\\*\\\/))|\\s*+;\\s*+(})\\s*+|\\s*+([*$~^|]?+=|[{};,>~+]|\\s*+-(?![0-9\\.])|!important\\b)\\s*+|([[(:])\\s++|\\s++([])])|\\s++(:)\\s*+(?!(?>[^{}\"\\']++|\"(?:[^\"\\\\\\]++|\\\\\\.)*+\"|\\'(?:[^\\'\\\\\\\\]++|\\\\\\.)*+\\')*+{)|^\\s++|\\s++\\z|(\\s)\\s+#si',\r\n            \/\/ Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`\r\n            '#(?<=[\\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',\r\n            \/\/ Replace `:0 0 0 0` with `:0`\r\n            '#:(0\\s+0|0\\s+0\\s+0\\s+0)(?=[;\\}]|\\!important)#i',\r\n            \/\/ Replace `background-position:0` with `background-position:0 0`\r\n            '#(background-position):0(?=[;\\}])#si',\r\n            \/\/ Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space\r\n            '#(?<=[\\s:,\\-])0+\\.(\\d+)#s',\r\n            \/\/ Minify string value\r\n            '#(\\\/\\*(?>.*?\\*\\\/))|(?<!content\\:)([\\'\"])([a-z_][a-z0-9\\-_]*?)\\2(?=[\\s\\{\\}\\];,])#si',\r\n            '#(\\\/\\*(?>.*?\\*\\\/))|(\\burl\\()([\\'\"])([^\\s]+?)\\3(\\))#si',\r\n            \/\/ Minify HEX color code\r\n            '#(?<=[\\s:,\\-]\\#)([a-f0-6]+)\\1([a-f0-6]+)\\2([a-f0-6]+)\\3#i',\r\n            \/\/ Replace `(border|outline):none` with `(border|outline):0`\r\n            '#(?<=[\\{;])(border|outline):none(?=[;\\}\\!])#',\r\n            \/\/ Remove empty selector(s)\r\n            '#(\\\/\\*(?>.*?\\*\\\/))|(^|[\\{\\}])(?:[^\\s\\{\\}]+)\\{\\}#s'\r\n        ),\r\n        array(\r\n            '$1',\r\n            '$1$2$3$4$5$6$7',\r\n            '$1',\r\n            ':0',\r\n            '$1:0 0',\r\n            '.$1',\r\n            '$1$3',\r\n            '$1$2$4$5',\r\n            '$1$2$3',\r\n            '$1:0',\r\n            '$1$2'\r\n        ),\r\n    $input);\r\n}\r\n\/\/ JavaScript Minifier\r\nfunction minify_js($input) {\r\n    if(trim($input) === \"\") return $input;\r\n    return preg_replace(\r\n        array(\r\n            \/\/ Remove comment(s)\r\n            '#\\s*(\"(?:[^\"\\\\\\]++|\\\\\\.)*+\"|\\'(?:[^\\'\\\\\\\\]++|\\\\\\.)*+\\')\\s*|\\s*\\\/\\*(?!\\!|@cc_on)(?>[\\s\\S]*?\\*\\\/)\\s*|\\s*(?<![\\:\\=])\\\/\\\/.*(?=[\\n\\r]|$)|^\\s*|\\s*$#',\r\n            \/\/ Remove white-space(s) outside the string and regex\r\n            '#(\"(?:[^\"\\\\\\]++|\\\\\\.)*+\"|\\'(?:[^\\'\\\\\\\\]++|\\\\\\.)*+\\'|\\\/\\*(?>.*?\\*\\\/)|\\\/(?!\\\/)[^\\n\\r]*?\\\/(?=[\\s.,;]|[gimuy]|$))|\\s*([!%&*\\(\\)\\-=+\\[\\]\\{\\}|;:,.<>?\\\/])\\s*#s',\r\n            \/\/ Remove the last semicolon\r\n            '#;+\\}#',\r\n            \/\/ Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}`\r\n            '#([\\{,])([\\'])(\\d+|[a-z_][a-z0-9_]*)\\2(?=\\:)#i',\r\n            \/\/ --ibid. From `foo['bar']` to `foo.bar`\r\n            '#([a-z0-9_\\)\\]])\\[([\\'\"])([a-z_][a-z0-9_]*)\\2\\]#i'\r\n        ),\r\n        array(\r\n            '$1',\r\n            '$1$2',\r\n            '}',\r\n            '$1$3',\r\n            '$1.$3'\r\n        ),\r\n    $input);\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"

Minification is technique used in which we remove all unnecessary Whitespaces Which include tab, space, newline, carriage return etc. This is done just to reduce data transfer. Since not everyone is serving a million hits a seconds – minifying html doesn’t help much, Instead enabling GZIP compression is a better technique. Apart from this – … <\/p>\n

Continue reading<\/a><\/p>\n","protected":false},"author":4,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_lock_modified_date":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[7,13,6],"tags":[17,18],"class_list":["post-81","post","type-post","status-publish","format-standard","hentry","category-css","category-javascript","category-server","tag-optimization","tag-server","item-wrap"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack-related-posts":[],"jetpack_shortlink":"https:\/\/wp.me\/pciGs2-1j","jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/posts\/81","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/comments?post=81"}],"version-history":[{"count":7,"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/posts\/81\/revisions"}],"predecessor-version":[{"id":91,"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/posts\/81\/revisions\/91"}],"wp:attachment":[{"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/media?parent=81"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/categories?post=81"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/madhurendra.com\/wp-json\/wp\/v2\/tags?post=81"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}