Access JSON data returned by SendGrid - php

I am working with the SendGrid PHP Library (https://sendgrid.com/docs/Integrate/Code_Examples/php.html).
The response is sent ass JSON - e.g. should be something like:
{"message":"success"}
I can send a simple email via:
<?php
$root="../../";
require $root . 'vendor/autoload.php';
$sendgrid = new SendGrid($SendGrid);
$email = new SendGrid\Email();
$email
//->addTo('you#me.com')
->addTo('you#me.com')
->setFrom('me#bar.com')
->setSubject('Subject goes here')
->setText('Hello World!')
->setHtml('<strong>Hello World!</strong>')
;
$res = $sendgrid->send($email);
?>
When I display the output of $res e.g. using PHP-REF (https://github.com/digitalnature/php-ref) I can see that it looks like this:
It appears the response is an Object - presumably JSON?
However, I can't access the data as JSON because if I try this:
$newtxt = json_decode($res);
I get this error:
Warning: json_decode() expects parameter 1 to be string, object given in C:\xampp\htdocs\jim\001-jimpix\contact_old\test-send-grid.php on line 24
And if I try this:
$j_array = json_decode($res, true);
I get the same error.
I can hard code the "$res" value as:
$res = "{\"message\":\"success\"}";
And then that works.
However, I can't work out how to access the JSON returned by SendGrid.
I've tried various things like:
$res = json_decode(json_encode($res),TRUE);
Presumably there is a way to access the JSON returned by SendGrid so I can access the JSON data.
But I don't know how?

As you can see from the PHP-REF response, $res is not the raw JSON.
You can access the result simply by using $res->getBody(). This will give you the parsed JSON from SendGrid.
You do not need to json_decode this.

Related

Get the value from Rest post API

Output when success
string(66)
"{"status":true,"message":"success","data":{"amountDue":"-504.20"}}"
Output when error
string(119) "{"status":false,"message":"An error occured while getting
full subscriber profile: Subscription not found MPP servers"}"
How should I write in php to get the amount due from the output? I am new to REST api. Can someone show me ? Thank you
That is a JSON-encoded response. Use json_decode() to convert the string back into an array, and then access the array element:
$output = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$results = json_decode($output,true);
if($results["status"])
{
echo "Success! Data: " . print_r($results,true);
}
I assume that you can at least send proper request to the endpoint and you are able to capture the response.
You receive a json string which must be parses so if:
$response = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$responseArray = json_decode($response, true);
Then you will get a responseArray as associated array (the second parameter) so you can get amount due like that
$amountDue = $responseArray['data']['amountDue'];
You could also parse json data into an StdClass which turn all fields in json into an object's property. To do that abandon the second parameter in json_decode function
$resultObj = json_decode($response);
$amountDue = $resultObj->data['amountDue'];
All depends on your requests.
To read more about json_decode try documentation

How to use Nominatim API through PHP to retrieve latitude and longitude?

Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.

Problems manipulating JSON data in PHP

I'm not that handy with JSON so here goes. I'm receiving Amazon SNS notifications for bouncing email addresses to a listener (in PHP 5.5) which does:
$post = #file_get_contents("php://input");
$object = json_decode($post, true);
This gives me:
Type => Notification
MessageId => #####
TopicArn => #####
Message => {
"notificationType":"Bounce",
"bounce": {
"bounceSubType":"General",
"bounceType":"Permanent",
"bouncedRecipients":[{"status":"5.3.0","action":"failed","diagnosticCode":"smtp; 554 delivery error: dd This user doesn't have a yahoo.com account (testuser#yahoo.com) [0] - mta1217.mail.bf1.yahoo.com","emailAddress":"testuser#yahoo.com"}],
"reportingMTA":"dsn; ######",
"timestamp":"2014-10-27T16:37:42.136Z",
"feedbackId":"######"
},
"mail": {
"timestamp":"2014-10-27T16:37:40.000Z",
"source":"myemail#mydomain.com",
"messageId":"######",
"destination":["testuser#yahoo.com"]
}
}
I was expecting an associative array all the way down but instead it's an array only at the top level and with JSON strings inside. I've tried everything I can think of, including json_decoding further parts of the array, but I'm struggling to access the data in a simple way. What I need is the "destination" email address which should be in $object['Message']['mail']['destination'][0].
Can anyone point out what I'm doing wrong here? Thanks.
It looks like $object['Message'] is also json encoded. Perhaps because it's using some generic container format for service call results. Try this
$post = #file_get_contents("php://input");
$object = json_decode($post, true);
//Message contains a json string
$object['Message'] = json_decode($object['Message'], true);
//Then access the structure using array notation
echo $object['Message']['mail']['destination'][0];

Instagram Real time API - PHP - Unable to get POST Update

I'm trying to connect with the instagram API, the connection works fine and I am receiving the updates just as described in the API documentation, the issue is that I cannot access to the data send to my callback function.
According to the doc
When someone posts a new photo and it triggers an update of one of your subscriptions, we make a POST request to the callback URL that you defined in the subscription
This is my code :
// check if we have a security challenge
if (isset ($_GET['hub_challenge']))
echo $_GET['hub_challenge'];
else // This is an update
{
// read the content of $_POST
$myString = file_get_contents('php://input');
$answer = json_decode($myString);
// This is not working starting from here
$id = $answer->{'object_id'};
$api = 'https://api.instagram.com/v1/locations/'.$id.'/media/recent?client_secret='.INSTA_CLI_SECRET.'&client_id='.INSTA_CLI_ID;
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
$decode = json_decode($response);
foreach($decode->{'data'} as $item){
// do something with the data here
}
}
}
Displaying the $myString variable I have this result, don't know why it is not decoded to json :(
[{"changed_aspect": "media", "subscription_id": 2468174, "object":
"geography", "object_id": "1518250", "time": 1350044500}]
the get_curl function is working fine when I hardcode my $id.
I guess something is wrong with my $myString, unfortunately the $_POST cvariable is not populated, Any idea what I am missing ?
Looking at the example JSON response included in your question, I can conclude that the object you are trying to talk with is wrapped in an array (hence the [ and ] around it in the JSON string).
You should access it using $answers[0]->object_id.
If that doesn't work, you can always use var_dump to check out the data in one of your variables.

Accessing tweets from home timeline in Twitter using oAuth in PHP?

I am trying to print the first tweet in the user timeline.
$hometimeline = $twitterObj->get_statusesHome_timeline();
$stream=$hometimeline->responseText;
$user=$stream[0]->user;
$tweet=$user->text;
echo $tweet;
This just won't print anything. What am I doing wrong here?
If I echo $hometimeline->responseText it shows on the screen
[
{"in_reply_to_status_id_str":null, "coordinates":null, "geo":null, "user":{"profile_use_background_image":true,"text":"I am back",....},"id_str":"121212"},
{ ... so on}
]
you are getting a json string as response. Use json_decode to parse the response and you will be able to manage it as array o stdobject
do this just before interact with the response
$stream = json_decode( $hometimeline->responseText, true);
Edit
remember you can always use print_r to debug
Try this instead:
$hometimeline = $twitterObj->get_statusesHome_timeline();
$stream = json_decode( $hometimeline->responseText );
$user=$stream[0]->user;
$tweet=$user->text;
echo $tweet;
json_decode turns the JSON string that you are receiving into a PHP object.

Categories