How to json_encode PHP object returned by Google Calendar API How to json_encode PHP object returned by Google Calendar API json json

How to json_encode PHP object returned by Google Calendar API


So, the problem, as you pointed out, is that properties you want to access are protected and json_encode respects that and will not access them. Read up on public, private, and protected. Good stuff

Because the values are protected, you'll have to pull the data you want out of $event and into an unprotected array and then json_encode that. Untested code follows:

$eventsArgs = array(    'maxResults' => 10,    'singleEvents' => true,);$events = $calendarService->events->listEvents('***@gmail.com', $eventsArgs);$listEvents = fopen('list_events.json', 'w');foreach($events->getItems() as $event) {    $jsonArr = array(        "start"=>$event->start->dateTime        ,"end"=>$event->end->dateTime    );    fwrite($listEvents, json_encode($jsonArr, JSON_PRETTY_PRINT));}fclose($listEvents);

Now even that code might not work. You may have to find the appropriate method (that's 'method' as in: function belonging to a class) to get the properties you want out of a Google Calendar Event, and then put them in an array and than json_encode it.

So the 'getter' method might be: $event->get('start')->dateTime or something. I have no experience with the Google Calendar API, so can't really help you in that regard

Lastly, know that you can have the PHP script echo the json_encoded results so you won't need the file. (of course, I have no idea what all of your code looks like, so that could be a bad idea)

foreach(...) {    echo json_encode($yourArray);}


I had the exact same problem as you! I finally found:

$json = json_encode( (array)$events);

Answer is from another post:Here

Please Note:


It produces Unicode NUL characters: \u0000*\u0000 on the outer array keys. But the full structure with the start and end values remains. If you are interested in removing the Nul chars you can use str_replace() or explode. Understanding what \u0000 is in PHP / JSON and getting rid of it

Terminus's answer above is great but using this was preferable for my situation because I needed to match a different json file from google node.js api .