Get the value from Rest post API - php

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

Related

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.

PHP: SOAP Webservice with JSON responce

I am developing a webservice in PHP using SOAP and I have to return the response in JSON format. Webservice method is simple. It takes an array as input and should return JSON object. Registering the method in webservice is like this:
$server->register(
'getProducts',
array('arr' => 'xsd:array'),
array('return' => 'xsd:json')
);
And I am doing this inside the method:
$sql3 = "SELECT name, price from products WHERE status_id=$staus_id and cat_id=$cat_id";
$result3 = $conn->query($sql3);
$row3 = mysqli_fetch_all($result3, MYSQLI_ASSOC);
$json = json_encode($row3);
return $json;
Whereas on client side I am doing this to catch the object and echo it:
$response = $client->getProducts($param);
echo $response;
But When I run the client side script, it gives nothing (an empty json object):
When I change the return type of the method to string in $server->register and I return an actual string in the method, it works fine but it doesn't in case of JSON object. Any help?
I am guessing here, since you did a json_encode on the server side, you must do a json_decode on the client side.
Change the code on the last line from:
echo $json;
to
echo json_decode($json);

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];

Empty string returned in Google Reverse geocoding webservice JSON

I have tried to use Reverse geocoding Webservice in PHP.Response JSON returns Empty response only.
$json_string2='http://maps.googleapis.com/maps/api/geocode/json?latlng=11.49813514,77.24331624&sensor=false';
$obj2=json_decode($json_string2);
$addr2=$obj2->formatted_address;
echo $addr2; //**line 1**
here line 1 prints empty....What is the problem in the coding....
Your problem is you did not get the file before decode to JSON and you also called with the wrong format.
$json_string2 = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=11.49813514,77.24331624&sensor=false');
$obj2 = json_decode($json_string2);
$addr2 = $obj2->results[0]->formatted_address;
echo $addr2; //**line 1**
you could try to print this object before you call its format.
print_r($obj2);

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