11 September 2019

This class provides several static functions for handling JSON data in PHP. These functions include options for encoding, decoding, and outputting JSON, and are intended to be independent of the user's current system. This means that the class can be used in any PHP environment and will produce consistent results.

One of the key features of this class is the ability to ensure that the correct encoding is used for JSON data. This is important because incorrect encoding can lead to errors and unexpected behavior when working with JSON data. The class also sets the appropriate headers when outputting JSON, which is important for ensuring that the data is properly interpreted by the client.

Another benefit of using this class is that it reduces the amount of code that needs to be written when working with JSON in PHP. By providing a set of static functions that can be easily used, this class simplifies the process of working with JSON data. This can help to make code more readable and maintainable, and can also save time when developing applications.

Source code viewer
  1. class Json {
  2. public static function jsonDecode($string) {
  3. // Decode json as associative array.
  4. return json_decode($string, TRUE);
  5. }
  7. public static function jsonEncode($var) {
  8. // Encode json while encoding all the necessary characters <, >, ', &, and ".
  9. return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  10. }
  12. public static function jsonOutput($var = NULL) {
  13. // Set correct header for json output.
  14. header('Content-Type: application/json');
  15. // Echo encoded json when output is set.
  16. if (isset($var)) {
  17. echo self::jsonEncode($var);
  18. }
  19. }
  21. }
Programming Language: PHP