This should do the trick!
// convert object => json
$json = json_encode($myObject);
// convert json => object
$obj = json_decode($json);
Here's an example
$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";
$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}
print_r(json_decode($json));
// stdClass Object
// (
// [hello] => world
// [bar] => baz
// )
If you want the output as an Array instead of an Object, pass true to json_decode
print_r(json_decode($json, true));
// Array
// (
// [hello] => world
// [bar] => baz
// )
More about json_encode()
See also: json_decode()
Answer from maček on Stack OverflowThis should do the trick!
// convert object => json
$json = json_encode($myObject);
// convert json => object
$obj = json_decode($json);
Here's an example
$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";
$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}
print_r(json_decode($json));
// stdClass Object
// (
// [hello] => world
// [bar] => baz
// )
If you want the output as an Array instead of an Object, pass true to json_decode
print_r(json_decode($json, true));
// Array
// (
// [hello] => world
// [bar] => baz
// )
More about json_encode()
See also: json_decode()
for more extendability for large scale apps use oop style with encapsulated fields.
Simple way :-
class Fruit implements JsonSerializable {
private $type = 'Apple', $lastEaten = null;
public function __construct() {
$this->lastEaten = new DateTime();
}
public function jsonSerialize() {
return [
'category' => $this->type,
'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
];
}
}
echo json_encode(new Fruit()); //which outputs:
{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}
Real Gson on PHP :-
- http://jmsyst.com/libs/serializer
- http://symfony.com/doc/current/components/serializer.html
- http://framework.zend.com/manual/current/en/modules/zend.serializer.html
- http://fractal.thephpleague.com/ - serialize only
passing JSON object through PHP
Get JSON object from PHP using javascript - JavaScript - SitePoint Forums | Web Development & Design Community
A simple tool i wrote to convert your JSON into PHP classes
JsonMapper: map a JSON response to your PHP objects
Hello everyone, I have the following javascript code in my project:
let questions = [
{
numb: 1,
question: "Question 1",
answer: "1.",
options: [
"some text",
"some text",
"some text",
"some text",
"some text"
]
},
{
numb: 2,
question: "Question 2",
answer: "2.",
options: [
"some text",
"some text",
"some text",
"some text",
"some text"
]
}];
Instead of having this array defined in my .js file, I want to make an XMLHttpRequest to a PHP script which will return this so it can be used in my JS, how can this be achieved? Sorry if this question is not well asked, I can't find the concept/terminology I'm looking for.