php 提供的字符串壓縮方法有
1.gzcompress — Compress a string
This function compress the given string using the ZLIB data format.
2.gzencode — Create a gzip compressed string
This function returns a compressed version of the input data compatible with the output of the gzip program
3.gzdeflate — Deflate a string
This function compress the given string using the DEFLATE data format.
4.bzcompress — 把一個字符串壓縮成 bzip2 編碼數據
bzcompress() 壓縮了指定的字符串並以 bzip2 編碼返回數據。
下面對這四種方法進行壓縮比較,分別進行中文和英文數字的壓縮
<?php
$str1 = '布局 1 介紹 布局,簡單來說就是設置元素的大小和位置。 Ext 的布局系統包括組件,布局,容器,容器是一種特殊的組件,可以管理組件的大小和位置。 容器是通過 doLayout 來重新計算布局,並更新 DOM. 2 手工布局是不必要的,框架會為你自動處理。';
$str2 = '!@#$%^&*()QWERTYUIOPSDFGHJKL!@#$%^&*()QWERTYUIOPSDFGHJKL:ZXCVBNMa!@#$%^&*()ERTYUIODFGHJKLXCVBNM@#$%^&*()RTYUIOPD:ZXCVBNM#!@#!@#$%^&*()QWERTYUIOPSDFGHJKL:ZXCVBNM-!@#$%^&*()ERTYUIODFGHJKLXCVBNM@#$%^&*()RTYUIOPD$%^&*()ERTYUIODFGHJ!@#$%^&*()QWERTYUIOPSDFGHJKL:ZXCVBNM]!@#$%^&*()ERTYUIODFGHJKLXCVBNM@#$%^&*()RTYUIOPDKLXCVBNM@#$%^&*()RTYUIOPDFGHJKLCVBNMFGHJTYU%^&RFGHJ4d56g7h8ui7h8ujirqwerqh8';
echo '<b>壓縮中文比較</b><br><br>';
compress_comp($str1, 1000); // 壓縮1000次 與 解壓縮1000次比較
echo '<b>壓縮英文數字比較</b><br><br>';
compress_comp($str2, 1000); // 壓縮1000次 與 解壓縮1000次比較
/* 壓縮 */
function compress_comp($str, $num){
$func_compress = array('gzcompress', 'gzencode', 'gzdeflate', 'bzcompress');
echo '原文:'.$str.'<br><br>';
echo '原文大小:'.strlen($str).'<br><br>';
for($i=0,$length=count($func_compress); $i<$length; $i++){
$starttime = get_microtime();
for($j=0; $j<$num; $j++){
switch($func_compress[$i]){
case 'gzcompress':
$mstr = gzcompress($str, 9); // 解壓方法:gzuncompress
break;
case 'gzencode':
$mstr = gzencode($str, 9); // 解壓方法:gzdecode php>=5.4
break;
case 'gzdeflate':
$mstr = gzdeflate($str, 9); // 解壓方法:gzinflate
break;
case 'bzcompress':
$mstr = bzcompress($str, 9); // 解壓方法:bzdecompress
break;
}
}
$endtime = get_microtime();
echo $func_compress[$i].' 壓縮後大小:'.strlen($mstr).' 耗時:'.round(($endtime-$starttime)*1000,5).'ms<br><br>';
}
}
/* 獲取 microtime */
function get_microtime(){
list($usec, $sec) = explode(' ', microtime(true));
return $usec+$sec;
}
?>
查看本欄目