I'm using Guzzle for HTTP Requests/Responses in my PHP project.
I'm sending the following request :
GET https://graph.microsoft.com/v1.0/me/events('[some_id]')
which, in Postman, returns something that looks like this :
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('...')/events/$entity",
"#odata.etag": "W/\"...==\"",
"id": "...",
"createdDateTime": "2018-06-14T08:03:44.5688916Z",
"lastModifiedDateTime": "2018-06-14T08:03:44.7407671Z",
"changeKey": "...==",
"categories": [],
"originalStartTimeZone": "UTC",
"originalEndTimeZone": "UTC",
"iCalUId": "...",
"reminderMinutesBeforeStart": 15,
"isReminderOn": true,
"hasAttachments": false,
"subject": "Created ?",
"bodyPreview": "",
"importance": "normal",
"sensitivity": "normal",
"isAllDay": false,
"isCancelled": false,
"isOrganizer": true,
"responseRequested": true,
"seriesMasterId": null,
"showAs": "busy",
"type": "singleInstance",
"webLink": "https://outlook.office365.com/owa/?itemid=...%3D&exvsurl=1&path=/calendar/item",
"onlineMeetingUrl": null,
"recurrence": null,
"responseStatus": {
"response": "organizer",
"time": "0001-01-01T00:00:00Z"
},
"body": {
"contentType": "html",
"content": ""
},
"start": {
"dateTime": "2018-06-15T10:00:00.0000000",
"timeZone": "UTC"
},
"end": {
"dateTime": "2018-06-15T13:30:00.0000000",
"timeZone": "UTC"
},
"location": {
"displayName": "",
"locationType": "default",
"uniqueIdType": "unknown",
"address": {},
"coordinates": {}
},
"locations": [],
"attendees": [],
"organizer": {
"emailAddress": {
"name": "...",
"address": "..."
}
}
}
So I build my request like this :
$client = new Client();
$header = array(
"Authorization" => "Bearer ".$token
);
$url = "https://graph.microsoft.com/v1.0/me/events('" .$idEvent. "')";
$request = new Request("GET", $url, $header, "");
try {
$eventInfos = $client->send($request);
}
catch (GuzzleException $e) {
var_dump($e->getMessage());
}
But when I var_dump($eventInfos), I get a GuzzleHttp\Psr7\Request object.
What is the correct way to get the JSON I was expecting please ?
You have to extract the body of from the response. Try this,
$client = new Client();
$header = array(
"Authorization" => "Bearer ".$token
);
$url = "https://graph.microsoft.com/v1.0/me/events('" .$idEvent. "')";
$request = new Request("GET", $url, $header, "");
try {
$eventInfos = $client->send($request);
$response = (string)$eventInfos->getBody();
}
catch (GuzzleException $e) {
var_dump($e->getMessage());
}
Also, you can use getContents() to get the response.
$request->getBody()->getContents()
Related
I am working on an application written in php 7.1.33 and for some unknown reason a strange behavior is occurring.
A function that returns the result of calling json_decode is returning a string. The code is similar to the following
public function post($url, array $body = [])
{
try
{
$client = $this->getClient();
$response = $client->request('POST', $url);
$content = $response->getBody()->getContents();
$output = json_decode($content);
return $content;
}
catch (ClientException $e)
{
echo $e->getMessage();
}
}
For some reason the call to the post function returns a string.
In fact, the problem is more complex for me because if you notice in this section
$content = $response->getBody()->getContents();
$output = json_decode($content);
return $content;
I must do it like this because if I try this way it returns null
return json_decode($response->getBody()->getContents());
The processed json is similar to this
'{
"id": 5895018,
"first_name": "Zu",
"last_name": "Mr",
"email": "zu.mr#bbking.com",
"phone": null,
"birthdate": null,
"postcode": null,
"address": null,
"city": null,
"country": null,
"gender": null,
"virtual_money": "0.0",
"money": "0.0",
"global_refundable_money": "0.0",
"balances": { "60402": 0.0, "60403": 0.0, "60464": 0.0, "60463": 0.0 },
"locale": "en",
"anonymous": false,
"refundable": true,
"family_id": null,
"family_owner": false,
"gtags": [],
"tickets": [],
"orders": []
}'
I have tried in my local that has php 7.4.9 to reproduce the scenario but the result is as expected
function simple_test() {
$json = '{"name": "ada", "last_name": "wong", "email": "ada.wong#umbrella.com"}';
return json_decode($json);
}
$output = simple_test();
var_dump($output);
Output is
class stdClass#1 (3) {
public $name =>
string(3) "ada"
public $last_name =>
string(4) "wong"
public $email =>
string(21) "ada.wong#umbrella.com"
}
What worries me is that moving this to production will cause a conflict
Thanks in advance for any ideas
You are returning $content that contains the return value of $response->getBody()->getContents(). You should return $output instead.
$content = $response->getBody()->getContents();
$output = json_decode($content);
return $output;
You can try convert same as :
$json= '{
"id": 5895018,
"first_name": "Zu",
"last_name": "Mr",
"email": "zu.mr#bbking.com",
"phone": null,
"birthdate": null,
"postcode": null,
"address": null,
"city": null,
"country": null,
"gender": null,
"virtual_money": "0.0",
"money": "0.0",
"global_refundable_money": "0.0",
"balances": { "60402": 0.0, "60403": 0.0, "60464": 0.0, "60463": 0.0 },
"locale": "en",
"anonymous": false,
"refundable": true,
"family_id": null,
"family_owner": false,
"gtags": [],
"tickets": [],
"orders": []
}';
$object = (object)$json;
$result = json_decode($object->scalar);
Link example
i am trying to get Youtube channel data with that api
https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&id={ Channel Id }&key={ API }
I used that code to fetch the data
if( $_SERVER[ 'REQUEST_METHOD' ] == 'GET' && !empty( $_GET ) ){
$channel_id = $_GET[ 'channel_id' ];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&id=". $channel_id ."&key=AIzaSyCKAnI41bI4UGDJgYUcwrhrIfnjoD3uirM",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
?>
<form id="channelIdForm" action="<?php $_SERVER['PHP_SELF']; ?>" method="get">
<input type="text" placeholder="Type channel id" name="channel_id" id="channelId" />
<button type="submit">Get data</button>
</form>
And it appeared like that
{ "kind": "youtube#channelListResponse", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/pss5QFB6saoevVwzX-8y6f1U75E\"", "pageInfo": { "totalResults": 1, "resultsPerPage": 1 }, "items": [ { "kind": "youtube#channel", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/gPFze0Hh7eRu9O5tXiTBVyvCwa8\"", "id": "UC4QYTjhWMxiC6UwvKLVkDDA", "snippet": { "title": "حفيد برايز حفيد برايز", "description": "", "publishedAt": "2018-04-01T17:18:31.000Z", "thumbnails": { "default": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s88-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 88, "height": 88 }, "medium": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s240-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 240, "height": 240 }, "high": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s800-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 800, "height": 800 } }, "localized": { "title": "حفيد برايز حفيد برايز", "description": "" } }, "contentDetails": { "relatedPlaylists": { "uploads": "UU4QYTjhWMxiC6UwvKLVkDDA", "watchHistory": "HL", "watchLater": "WL" } }, "statistics": { "viewCount": "830460", "commentCount": "0", "subscriberCount": "3741", "hiddenSubscriberCount": false, "videoCount": "19" } } ] }
Then i tried to convert that json to an array to pick what i want from it with index
So i tried that instead of $response
$json = $response;
$arr = json_decode($json, true);
$row = array_reduce($arr['items'], function($c, $v){
$c[ key($v) ] = current($v);
return $c;
}, array());
print_r( $row );
I expected to see all the indexes below item but the result was
Array ( [kind] => youtube#channel )
It show just kind i don't know what the problem with so if any one can help i will be appreciated!!
The array_reduce function reduces an array to a single value. But it appears you are interested in multiple key/value pairs. Since json_decode($json, true); already provides you with an associated array you can retrieve specific keys via their names. Example:
$arr = json_decode($response, true);
$newArray = [];
$requiredKeys = ['kind','etag'];
foreach ($requiredKeys as $key){
$newArray[$key] = $arr[$key];
}
It is a very-multi-dimensional array.
Here's some code that prints the contents of an array. If the value it is going to print is an array, it calls itself again. You'll see it puts out Printing $json_arr[items[0][statistics] : followed by a bunch of key->value pairs, so you can find the state you want and you'll know what the parent array(s) are.
<?php
$json='{ "kind": "youtube#channelListResponse", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/pss5QFB6saoevVwzX-8y6f1U75E\"", "pageInfo": { "totalResults": 1, "resultsPerPage": 1 }, "items": [ { "kind": "youtube#channel", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/gPFze0Hh7eRu9O5tXiTBVyvCwa8\"", "id": "UC4QYTjhWMxiC6UwvKLVkDDA", "snippet": { "title": "حفيد برايز حفيد برايز", "description": "", "publishedAt": "2018-04-01T17:18:31.000Z", "thumbnails": { "default": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s88-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 88, "height": 88 }, "medium": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s240-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 240, "height": 240 }, "high": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s800-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 800, "height": 800 } }, "localized": { "title": "حفيد برايز حفيد برايز", "description": "" } }, "contentDetails": { "relatedPlaylists": { "uploads": "UU4QYTjhWMxiC6UwvKLVkDDA", "watchHistory": "HL", "watchLater": "WL" } }, "statistics": { "viewCount": "830460", "commentCount": "0", "subscriberCount": "3741", "hiddenSubscriberCount": false, "videoCount": "19" } } ] } ';
$json_arr=json_decode($json,true);
function print_array($prefix,$arr){
print("printing ".$prefix." :\n");
foreach($arr as $k=>$v){
if(is_array($v)){
print_array($prefix."[".$k."]",$v);
}else{
print("key: ".$k." value:".$v." \n");
}
}
return;
}
print_array("\$json_arr",$json_arr);
?>
I have this php code to return the Array from a JSON file how ever I am not able to return the objects (The Airport info structure) as well the Arrivals etc.
Apologies if this is not very clear I am fairly new to this.
Code:
$fxml_response = $client->request('GET', 'AirportBoards', ['query' => $queryParams]);
try {
$body = json_decode($fxml_response->getBody(), true);
if ($fxml_response->getStatusCode() == 200 && !array_key_exists('error', $body)) {
foreach (['arrivals', 'departures', 'enroute', 'scheduled',] as $board) {
if($body['AirportBoardsResult'][$board]) {
$boardFlights = $body['AirportBoardsResult'][$board]['flights'];
$response[$board] = $boardFlights;
}
}
} else {
$response['error'] = $body['error'];
}
} catch (Exception $e) {
echo json_encode(['error' => 'Failed to retrieve Airport Board details.']);
}
// Send back the data
header('Content-Type: application/json');
echo json_encode($response);
Json:
{
"AirportBoardsResult": {
"airport": "NZAP",
"airport_info": {
"airport_code": "NZAP",
"name": "Taupo",
"elevation": 1335.0,
"city": "Taupo",
"state": "",
"longitude": 176.084444,
"latitude": -38.739723,
"timezone": ":Pacific/Auckland",
"country_code": "NZ",
"wiki_url": "https://en.wikipedia.org/wiki/Taupo_Airport",
"alternate_ident": "TUO"
},
"arrivals": {
"num_flights": 6,
"next_offset": -1,
"flights": [{
"ident": "SDA806",
"faFlightID": "SDA806-1528092600-schedule-0000",
"airline": "SDA",
"airline_iata": "S8",
"flightnumber": "806",
"tailnumber": "ZK-PLV",
"type": "Form_Airline",
"blocked": false,
"diverted": false,
"cancelled": false,
"origin": {
"code": "NZWN",
"city": "Wellington",
"alternate_ident": "WLG",
"airport_name": "Wellington Int'l"
},
"destination": {
"code": "NZAP",
"city": "Taupo",
"alternate_ident": "TUO",
"airport_name": "Taupo"
},
"filed_ete": 3480,
"route": "KADNU1Q KAPTI WNAP2",
"filed_altitude": 210,
"display_filed_altitude": "21,000 feet",
"filed_airspeed_kts": 250,
"distance_filed": 191,
"filed_departure_time": {
"epoch": 1528265400,
"tz": "NZST",
"dow": "Wednesday",
"time": "06:10PM",
"date": "06/06/2018",
"localtime": 1528308600
},
"estimated_departure_time": {
"epoch": 1528265889,
"tz": "NZST",
"dow": "Wednesday",
"time": "06:18PM",
"date": "06/06/2018",
"localtime": 1528309089
},
"actual_departure_time": {
"epoch": 1528265889,
"tz": "NZST",
"dow": "Wednesday",
"time": "06:18PM",
"date": "06/06/2018",
"localtime": 1528309089
},
"departure_delay": 489,
"filed_arrival_time": {
"epoch": 1528268880,
"tz": "NZST",
"dow": "Wednesday",
"time": "07:08PM",
"date": "06/06/2018",
"localtime": 1528312080
},
"estimated_arrival_time": {
"epoch": 1528269502,
"tz": "NZST",
"dow": "Wednesday",
"time": "07:18PM",
"date": "06/06/2018",
"localtime": 1528312702
},
"actual_arrival_time": {
"epoch": 1528269180,
"tz": "NZST",
"dow": "Wednesday",
"time": "07:13PM",
"date": "06/06/2018",
"localtime": 1528312380
},
"arrival_delay": 300,
"status": "Arrived",
"progress_percent": 100,
"aircrafttype": "PC12",
"full_aircrafttype": "L/PC12",
"adhoc": false
}]
};
Add the airport info to the result after the loop.
if ($fxml_response->getStatusCode() == 200 && !array_key_exists('error', $body)) {
foreach (['arrivals', 'departures', 'enroute', 'scheduled',] as $board) {
if($body['AirportBoardsResult'][$board]) {
$boardFlights = $body['AirportBoardsResult'][$board]['flights'];
$response[$board] = $boardFlights;
}
}
$response['airport_info'] = $body['AirportBoardsResult']['airport_info'];
}
I have a trouble with JSON in PHP.
I have a JSON structure like this (with some line is const and some line is variable)
{
"user": {
"lam": {---->variable
"\/lam\/files\/a": { ---->variable
"id": 9, ---->variable
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498", ---->variable
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=" ---->variable
}
}
}
}
}
I don't know how to write this content to file as JSON format like this.
And in a number of case, I must write append to this file and result must like this:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You could create an array, before to use json_encode():
Here is an example.
// prepare an array with variable (should come from database, or whatever)
$vars = [
[
'user' => 'lam',
'path' => '/lam/files/a',
'id' => 9,
'bucket' => 'lam-15215156681752265498',
'pass' => 'NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=',
],
[
'user' => 'lam',
'path' => '/lam/files/test',
'id' => 12,
'bucket' => 'lam-152153961597103330',
'pass' => 'MjdzcDlrenptcG5udzI2MLSQvuGIczY/SyHZVf9o7e8=',
]
];
// prepare data to be encoded.
$data = [];
// iterate over the variables,
foreach ($vars as $var) {
// prepare an array for the options
$options = [
"user" => "owncloud",
"bucket" => $var['bucket'], // fill with current variable
"password" => "",
"region" => "regionOne",
"service_name" => "swift",
"tenant" => "owncloud",
"timeout" => "30",
"url" => "http:\/\/controller:5000\/v2.0",
"password_encrypted" =>$var['pass'], // fill with current variable
];
$userdata = [
'id' => $var['id'], // fill with current variable
'class' => '\\OC\\Files\\Storage\\Swift',
'options' => $options, // append options
];
$name = $var['user'];
$path = $var['path'];
$data['user'][$name][$path] = $userdata ; // append to $data array
}
echo json_encode($data, JSON_PRETTY_PRINT);
Outputs:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You'll need to work with the data as an array (or object) as PHP won't work directly in JSON;
Get your current data from the file into an array:
$data = json_decode(file_get_contents($pathtojsonfile, true));
Append the new data to the array:
$data[] = $newdata;
Then save the newly appended data back to file.
file_put_contents($pathtojsonfile, json_encode($data));
Need help with the following I writing a webhook in php, and need the ability to read the context parameters.
Can someone help me to understand how it can be done?
Here is my example JSON:
{
"id": "6e774dc2-2323-42b3-bd3c-ab64930f8b92",
"timestamp": "2017-12-22T21:12:19.094Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "Yes",
"action": "Triage.Triage-yes",
"actionIncomplete": false,
"parameters": {},
"contexts": [
{
"name": "triage-followup",
"parameters": {
"triagecriteria": [],
"roomEntity.original": "",
"roomname": "300",
"roomnames.original": "living",
"roomid": "200",
"context": "",
"roomnames": [
"living"
],
"counter": "400",
"roomEntity": "100",
"triagecriteria.original": ""
},
"lifespan": 3
}
],
"metadata": {
"intentId": "ecd4a2e5-65a0-41b2-ac72-edcf4d2e73f2",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 203,
"intentName": "Triage - yes"
},
"fulfillment": {
"speech": "Yes",
"source": "agent",
"displayText": "No",
"messages": [
{
"type": 0,
"speech": "Yes"
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success",
"webhookTimedOut": false
},
"sessionId": "db8c1a4e-fa0c-4257-a536-78b63879eef9"
}
I want to be able to refer to [results][Contexts][Parameters]
I am using
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true, 512, JSON_BIGINT_AS_STRING);
and trying to access the value as $update["results"]["Contexts"]["Parameters"]["roomid"]
The names are case sensitive, and you need to be careful about trailing "s"es. Since some of the items are numerically indexed arrays, you'll need to include that as part of the index. Try
$update["result"]["contexts"][0]["parameters"]["roomid"]