The method of compressing gzcompress and decompressing gzuncompress string in php, suitable for big data content scenarios

  Driven by big data, the amount of data is increasing, and in the era where content is king, the data table is bigger and more inflated, resulting in slower data return when reading the data table and slower access to content pages. If you can keep the content unchanged, compressing the content is undoubtedly a kind of website optimization. If the length of each content is compressed to 100 times and 1000 times of the previous content, the overall data table will reduce the storage of several gigabytes or tens of gigabytes, and the speed of returning data when reading data will also increase. The following shares the method of compressing data in php, hoping to bring help to those in need.

  1. /**
  2. * Determine if the string is base64 encoded
  3. */
  4. function func_is_base64($str)
  5. {
  6. return $str == base64_encode(base64_decode($str)) ? true : false;
  7. }
  8. /**
  9. * Compressed content
  10. */
  11. function func_gzcompress($str, $level = 9)
  12. {
  13. if (!func_is_base64($str)) {
  14. return base64_encode(gzcompress($str, $level));
  15. }
  16. return $str;
  17. }
  18. /**
  19. * Unzip the content
  20. */
  21. function func_gzuncompress($str)
  22. {
  23. if (func_is_base64($str)) {
  24. return gzuncompress(base64_decode($str));
  25. }
  26. return $str;
  27. }

    In addition to gzcompress, the compression methods include gzdeflate, gzencode, and bzcompress. After testing by netizens, the results are as follows:

    gzcompress is the fastest and has a higher compression ratio. 

    gzdeflate has the highest compression ratio, slightly slower than gzcompress 

    gzencode is close to gzdeflate, gzdeflate has a slight advantage 

    bzcompress is the slowest and has the slowest compression ratio. 

    Therefore it is recommended to use gzcompress and gzdeflate.


Related: The method of compressing gzcompress and decompressing gzuncompress string in php, suitable for big data content scenarios