1. <?php
  2. /**
  3. * Compresses JSON payloads for routine automation with verbose logging.
  4. *
  5. * @param string $jsonPayload The JSON payload to compress.
  6. * @return string|false The compressed JSON payload, or false on error.
  7. */
  8. function compressJsonPayload(string $jsonPayload): string|false
  9. {
  10. // Verbose logging - log the input payload
  11. error_log("Input JSON Payload:\n" . $jsonPayload);
  12. try {
  13. // Decode the JSON payload
  14. $data = json_decode($jsonPayload, true);
  15. if ($data === null) {
  16. error_log("Error decoding JSON: " . json_last_error_msg());
  17. return false; // Return false on decoding error
  18. }
  19. // Compress the decoded data. Using gzencode for compression
  20. $compressedData = gzencode(json_encode($data), 9, GZ_COMPRESSION_DEFLATE);
  21. // Verbose logging - log the compressed data
  22. error_log("Compressed JSON Payload:\n" . $compressedData);
  23. return $compressedData;
  24. } catch (Exception $e) {
  25. error_log("An unexpected error occurred: " . $e->getMessage());
  26. return false; // Return false on unexpected errors
  27. }
  28. }
  29. // Example usage (for testing)
  30. /*
  31. $json = '{
  32. "name": "John Doe",
  33. "age": 30,
  34. "city": "New York",
  35. "details": {
  36. "occupation": "Software Engineer",
  37. "skills": ["PHP", "JavaScript", "MySQL"]
  38. }
  39. }';
  40. $compressed = compressJsonPayload($json);
  41. if ($compressed !== false) {
  42. echo "Compression successful.\n";
  43. // You can now use the $compressed variable for automation
  44. // For example, sending it to an API.
  45. } else {
  46. echo "Compression failed.\n";
  47. }
  48. */
  49. ?>

Add your comment