ajamil
answered Jun 24 '23 00:00
In PHP, you can convert an object to a JSON string using the json_encode() function. This function takes the object as input and returns a JSON-formatted string representing the object's data.
class MyClass {
public $property1;
public $property2;
public function __construct($prop1, $prop2) {
$this->property1 = $prop1;
$this->property2 = $prop2;
}
}
$obj = new MyClass("Value 1", "Value 2");
$jsonString = json_encode($obj);
echo $jsonString;
In this example, we have a MyClass with two public properties, $property1 and $property2. We create an instance of MyClass called $obj with some values assigned to its properties.
To convert the object $obj to a JSON string , we use the json_encode() function , passing $obj as the argument. The json_encode() function serializes the object into a JSON string representation .