1. <?php
  2. /**
  3. * Serializes objects from JSON responses for compatibility with older PHP versions.
  4. *
  5. * @param mixed $object The object to serialize.
  6. * @return string The JSON encoded string.
  7. */
  8. function serializeObjectToJson( $object ) {
  9. if ( is_object( $object ) ) {
  10. return json_encode( (array) $object, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ); // Convert object to array and encode
  11. } else {
  12. return json_encode( $object, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ); // Encode directly if not an object
  13. }
  14. }
  15. //Example Usage (for testing):
  16. /*
  17. class MyClass {
  18. public $name = "John Doe";
  19. public $age = 30;
  20. }
  21. $obj = new MyClass();
  22. $json = serializeObjectToJson($obj);
  23. echo $json . "\n";
  24. $data = ['key' => 'value', 'number' => 123];
  25. $json2 = serializeObjectToJson($data);
  26. echo $json2 . "\n";
  27. */
  28. ?>

Add your comment