11 September 2019

This snippet contains a small class that does most of the JSON operations that you might ever need. Static functions for encoding, decoding and outputting json from PHP. Ensure that you get the right encoding of json and set the right headers and not be dependent on you current system.

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. }
  6.  
  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. }
  11.  
  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. }
  20.  
  21. }
Programming Language: PHP