Store json response in a variable in php - php

I am trying to send json request and store the response in a variable using php using the below code
$hmaps_request = "https://geocoder.api.here.com/6.2/geocode.json?app_id=xxx&app_code=yyy&searchtext=3891 Delwood Drive, Powell, OH, United States";
$json = file_get_contents($hmaps_request);
$details = json_decode($json, TRUE);
I could not get anyerrors as well as any response. But if i paste the url in browser i could get json response.

Detects Your Problem
If you read the $http_response_header array (generated by file_get_contents() call), you'd find out that you got a "400 Bad Request" response and thus got nothing. So something must have gone wrong with your URL.
After a brief inspection, I think perhaps its your "searchtext" parameter that's blocking you. For starter, valid URL query don't usually have spaces in it. Probably why the API server says that you're a "Bad Request".
Normally, you need to properly escape the URL query string to have a proper URL. Modern browsers are very good at translating it for you seamlessly and automatically so you might not have this problem by using the URL directly in browsers.
Solution
Let's put this theory to a test. We'll use http_build_query() to escape your query query parameters:
(For privacy reason, the parameters are modified. Please substitute the query variables)
$query = http_build_query([
'app_id' => 'your-app-id',
'app_code' => 'your-app-code',
'searchtext' => '123 Some Address',
]);
$url = 'https://geocoder.api.here.com/6.2/geocode.json?' . $query;
$json = file_get_contents($url);
$details = json_decode($json, TRUE);
var_dump($details);
I seem to get proper decoded response now. Try it yourself.

There is an error in your request URL change the request URL
From
$hmaps_request = "https://geocoder.api.here.com/6.2/geocode.json?app_id=NT2iR8TD1kAeCxERIow8&app_code=-r9pZGDuz6G5NWToLaCSUQ&searchtext=3891 Delwood Drive, Powell, OH, United States";
To
$hmaps_request = "https://geocoder.api.here.com/6.2/geocode.json?app_id=NT2iR8TD1kAeCxERIow8&app_code=-r9pZGDuz6G5NWToLaCSUQ&searchtext=3891+Delwood+Drive+Powell+OH+United+States";
Here is the full code
$hmaps_request = "https://geocoder.api.here.com/6.2/geocode.json?app_id=NT2iR8TD1kAeCxERIow8&app_code=-r9pZGDuz6G5NWToLaCSUQ&searchtext=3891+Delwood+Drive+Powell+OH+United+States";
$json = file_get_contents($hmaps_request);
$details = json_decode($json, TRUE);
print_r($details);

I think the error in your request URL. Please check below code.
$url = "https://geocoder.api.here.com/6.2/geocode.json?app_id=NT2iR8TD1kAeCxERIow8&app_code=-r9pZGDuz6G5NWToLaCSUQ&searchtext=3891 Delwood Drive, Powell, OH, United States";
$url = str_replace(" ","%20",$url);
$json = #file_get_contents($url);
$details = json_decode($json, TRUE);
print_r($details);

Related

file_get_contents with Variable

Hey so I'm having a slight dilemma with getting the contents of a file using a variable.
So to explain the code below a little, the respform fetches JSON array all ok. And the results url when echo'd displays like a normal URL that when viewed displays JSON data. Then I want to fetch JSON data from the second URL. If I use this variable in file_get_contents nothing happens. If I simply create a variable $url = '' and type the same address it works fine.
I've var dumped the $resulturl variable that I'm using and it is a string(56). I've tried using json_encode and it becomes a string(64). What sort of data does it need to be to be accepted into the file_get_contents.
$resp = file_get_contents($url, FALSE, $context);
$respform = json_decode($resp, TRUE);
$resulturl = $respform['resultsUrl'];
$data = file_get_contents($resulturl, FALSE);
$insta_array = json_decode($data, TRUE);
print_r($insta_array);
Hope someone can help, Thanks!
$resulturl apparently contains a JSON-encoded URL. You need to do:
$resulturl = json_decode($respform['resultsUrl']);

Trying to get property of non-object geolocation google API

I'm working in to get the latitude and longitude from google maps through the geolocation API. I have tried many times but always is showing this error:
Trying to get property of non-object in C:\wamp64\www\index3.php on line 16
The issue is that I'm not able to get the info from the $url so then, cannot get the latitude and longitude.
I changed my code and now it is, but still with no working.
<php
$address = urlencode('BTM 2nd Stage,Bengaluru,Karnataka,560076');
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=*************************************";
$json = file_get_contents($url); // I tried with the # symbol and without it
$data=json_decode($json);
echo ($data->results[0]->geometry->location->lat);
?>
And also I used this one:
<php
$address = 'BTM 2nd Stage,Bengaluru,Karnataka,560076';
$encode = urlencode($address);
$key = "insert key here";
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$encode}&key={$key}";
$json = file_get_contents($url); // I tried with the # symbol and without it
$data = json_decode($json);
echo "Latitud".($data->results[0]->geometry->location->lat);
?>
Without the # symbol I have this error line
Warning: file_get_contents() has been disabled for security reasons in [...][...] on line 8
change http
to https in your request url.
As Abrucius, you msut use HTTPS or google will deny the request. You must also encode the address or else you will get a "Bad request" error.
<?php
$address = 'BTM 2nd Stage,Bengaluru,Karnataka,560076';
$encode = urlencode($address);
$key = "insert key here";
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$encode}&key={$key}";
$json = file_get_contents($url);
$data = json_decode($json);
echo ($data->results[0]->geometry->location->lat);
Outputs: 12.9082396
replace following code
$address = 'BTM 2nd Stage,Bengaluru,Karnataka,560076';
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&key=AIzaSyDjWI3J9CNlANoB5PXNKq3nz1ZbYeOrNGE";
to
$address = urlencode('BTM 2nd Stage,Bengaluru,Karnataka,560076');
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=AIzaSyDjWI3J9CNlANoB5PXNKq3nz1ZbYeOrNGE";
You have provided http in the url, it should be https. Try below code that will help you. You have to use urlencode() because api will not allow space in the address, so you have to encode.
$address = 'BTM 2nd Stage,Bengaluru,Karnataka,560076';
$address = urlencode($address);
$url = "https://maps.google.com/maps/api/geocode/json?address={$address}&key=***************************";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
echo "<pre>";print_r($resp["results"][0]['geometry']['location']['lat']);
Try this code will work for sure
WillParky93's answer seems to work fine for me. Maybe try following the next link to allow https wrappers:
How to get file_get_contents() to work with HTTPS?
...or post the error you're getting so we can help you out
I just solved this issue, I was getting this error because of a proxy configuration. I was testing into a network with a proxy configuration. So, the proxy is not allowing me to connect with the Google database. Then I tried to connect with a different network and it worked perfectly. Thank you guys for your aid!

Displaying information from JSON request

For the sake of having you guys being able to read what I'm doing, I will post this with the api key and then edit it after.
How do I display the information from this url?
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=UItqDZuHOsM&key=AIzaSyAQ26GN-removedapikey
I am using this code, but I don't understand the correct way to grab the json stuff. I've tried tons of different ways.
$vidkey = $vid_row['youtube_id'];
$apikey = "removed";
$json_output = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=$vidkey&key=$apikey");
$json = json_decode($json_output, true);
//video title
$you_title = $json['snippet']['title'];
I guess I don't understand the hierarchy of it all.
Use Below code to get Title :
$vidkey = $vid_row['youtube_id'];
$apikey = "**********";
$json_output = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=$vidkey&key=$apikey");
$json = json_decode($json_output, true);
echo $json['items'][0]['snippet']['title'];
Try do to a print_r($json) to understand what you're exactly doing. But just navigate in it as an object. In the current case just do:
$json['items'][0]['snippet']['title'];
But if you want to do it with a more easy way to do it (object way), just remove the true from your json_decode function
$json->items[0]->snippet->title;

Trouble Reading json Data from hasoffer API

Trying to read json Data and I can't get it to work correctly with the following code:
$apiurl = "https://api.hasoffers.com/Apiv3/json?NetworkId=REDACTED&Target=Affiliate_Report&Method=getStats&api_key=REDACTED&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.unique_clicks&fields%5B%5D=Stat.payout&filters%5BStat.date%5D%5Bconditional%5D=LESS_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21&filters%5BStat.date%5D%5Bconditional%5D=GREATER_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21";
$data = json_decode(file_get_contents($apiurl), true);
foreach($data['response']['data'] as $dataline) {
echo "Conversions: {$dataline['Stat']['conversions']} Payout: {$dataline['Stat']['payout']}";
}
The query is generating the following json return, I just can't figure out how to read the stats correctly (it's also looping through 7 lines in the foreach which also makes no sense to me):
{"request":{"Target":"Affiliate_Report","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"REDACTED","Method":"getStats","api_key":"REDACTED","fields":["Stat.conversions","Stat.unique_clicks","Stat.payout"],"filters":{"Stat.date":{"conditional":"GREATER_THAN","values":"2016-02-21"}},"__gaTune":"GA1.2.1289716345.1455904273","__utma":"267117079.1377304869.1455903853.1455904273.1455904273.1","__utmc":"267117079","__utmz":"267117079.1455904273.1.1.utmcsr=developers.hasoffers.com|utmccn=(referral)|utmcmd=referral|utmcct=/","_biz_uid":"1742fd1f613440a4cfbb5a510d1d7def","_biz_nA":"1","_biz_pendingA":"[]","_hp2_id_1318563364":"5257773084071598.0276720083.0714677778","_ga":"GA1.2.1377304869.1455903853"},"response":{"status":1,"httpStatus":200,"data":{"page":1,"current":50,"count":1,"pageCount":1,"data":[{"Stat":{"conversions":"1000","unique_clicks":"1000","payout":"1000.000000"}}],"dbSource":"branddb"},"errors":[],"errorMessage":null}}
If your JSON is exactly that you have posted, it is unvalid JSON, as per the comments.
The invalid part is the REDACTED words without double-quote.
To bypass this error, you can try in this way:
$data = file_get_contents( $apiurl );
$data = preg_replace( '/:REDACTED(?=\W)/', ':"REDACTED"', $data );
$json = json_decode( $data, True );
This will works on example above, but please note that is a trick, and it can not work if some JSON field has a value like "sometext:REDACTED,sometext": it is improbable, but not impossible.
Actually thank you that site helped a lot realized there was a second array also labeled "data" under the first "data" array so I needed to change it to:
$data['response']['data']['data'] as $dataline

Retrieving info from JSON array with PHP

i have this public JSON https://raw.github.com/currencybot/open-exchange-rates/master/latest.json and i need to extract data from it, right now i tried something like this:
$input = file_get_contents("https://raw.github.com/currencybot/open-exchange-rates/master/latest.json");
$json = json_decode($input);
echo $json[rates]->EUR;
but i obtain a blank page, any suggestion? Thanks !! Ste
json_decode either returns an object, or an array (when you use the second param). You are trying to use both.
Try:
$json = json_decode($input);
echo $json->rates->EUR;
OR
$json = json_decode($input, true);
echo $json['rates']['EUR'];
As to the blank page, please add the following to the top of your script:
error_reporting(E_ALL);
init_set('display_errors', true);
A 500 Error indicates you are unable to resolve that url using file_get_contents.
Check here for more information.
Read the help for json_decode ... without the second parameter it returns and object not an array ...
Either :
$json = json_decode($input);
echo $json->rates->EUR;
or
$json = json_decode($input,true);
echo $json['rates']['EUR'];
Try:
$arr = json_decode($input, true);
var_dump($arr);
echo $arr['rates']['EUR'];
Further Reading:
http://de.php.net/manual/de/function.json-encode.php
For anexample with cURL and SSL read this:
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
The link looks like starting with https, while file_get_contents can't deal with SSL. My suggestion is using curl.

Categories