How can nested objects be properly encoded to JSON in PHP?

When encoding nested objects to JSON in PHP, you can use the json_encode() function along with the JSON_FORCE_OBJECT option to ensure that nested objects are properly encoded as objects within the JSON string. This option will force all objects to be encoded as objects, even if they are empty.

// Sample nested objects
$nestedObject = new stdClass();
$nestedObject->key1 = "value1";
$nestedObject->key2 = "value2";

$mainObject = new stdClass();
$mainObject->nested = $nestedObject;

// Encode nested objects to JSON
$jsonString = json_encode($mainObject, JSON_FORCE_OBJECT);

echo $jsonString;