I have a URL that returns a JSON object like this:
{
"expires_in":5180976,
"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
}
I want to get JSON object from the URL and then the access_token value.
So how can I retrieve it through PHP?
$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;
For this to work, file_get_contents requires that allow_url_fopen is enabled. This can be done at runtime by including:
ini_set("allow_url_fopen", 1);
You can also use curl to get the url. To use curl, you can use the example found here:
$ch = curl_init();
// IMPORTANT: the below line is a security risk, read https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software
// in most cases, you should set it to true
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $obj->access_token;
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];
Php also can use properties with dashes:
garex#ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
public $qwert-y =>
int(123)
}
=> null
You could use PHP's json_decode function:
$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];
You need to read about json_decode function http://php.net/manual/en/function.json-decode.php
Here you go
$json = '{"expires_in":5180976,"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"}';
//OR $json = file_get_contents('http://someurl.dev/...');
$obj = json_decode($json);
var_dump($obj-> access_token);
//OR
$arr = json_decode($json, true);
var_dump($arr['access_token']);
// Get the string from the URL
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452');
// Decode the JSON string into an object
$obj = json_decode($json);
// In the case of this input, do key and array lookups to get the values
var_dump($obj->results[0]->formatted_address);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $obj->access_token;
file_get_contents() is not fetching the data from url,then i tried curl and it's working fine.
Our solution, adding some validations to response so we are sure we have a well formed json object in $json variable
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if (! $result) {
return false;
}
$json = json_decode(utf8_encode($result));
if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
return false;
}
my solution only works for the next cases:
if you are mistaking a multidimensaional array into a single one
$json = file_get_contents('url_json'); //get the json
$objhigher=json_decode($json); //converts to an object
$objlower = $objhigher[0]; // if the json response its multidimensional this lowers it
echo "<pre>"; //box for code
print_r($objlower); //prints the object with all key and values
echo $objlower->access_token; //prints the variable
i know that the answer was has already been answered but for those who came here looking for something i hope this can help you
When you are using curl sometimes give you 403 (access forbidden)
Solved by adding this line to emulate browser.
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
Hope this help someone.
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'https://www.xxxSite/get_quote/ajaxGetQuoteJSON.jsp?symbol=IRCTC&series=EQ');
//Set the GET method by giving 0 value and for POST set as 1
//curl_setopt($curl_handle, CURLOPT_POST, 0);
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$query = curl_exec($curl_handle);
$data = json_decode($query, true);
curl_close($curl_handle);
//print complete object, just echo the variable not work so you need to use print_r to show the result
echo print_r( $data);
//at first layer
echo $data["tradedDate"];
//Inside the second layer
echo $data["data"][0]["companyName"];
Some time you might get 405, set the method type correctly.
Related
I have a URL that returns a JSON object like this:
{
"expires_in":5180976,
"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
}
I want to get JSON object from the URL and then the access_token value.
So how can I retrieve it through PHP?
$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;
For this to work, file_get_contents requires that allow_url_fopen is enabled. This can be done at runtime by including:
ini_set("allow_url_fopen", 1);
You can also use curl to get the url. To use curl, you can use the example found here:
$ch = curl_init();
// IMPORTANT: the below line is a security risk, read https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software
// in most cases, you should set it to true
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $obj->access_token;
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];
Php also can use properties with dashes:
garex#ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
public $qwert-y =>
int(123)
}
=> null
You could use PHP's json_decode function:
$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];
You need to read about json_decode function http://php.net/manual/en/function.json-decode.php
Here you go
$json = '{"expires_in":5180976,"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"}';
//OR $json = file_get_contents('http://someurl.dev/...');
$obj = json_decode($json);
var_dump($obj-> access_token);
//OR
$arr = json_decode($json, true);
var_dump($arr['access_token']);
// Get the string from the URL
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452');
// Decode the JSON string into an object
$obj = json_decode($json);
// In the case of this input, do key and array lookups to get the values
var_dump($obj->results[0]->formatted_address);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $obj->access_token;
file_get_contents() is not fetching the data from url,then i tried curl and it's working fine.
Our solution, adding some validations to response so we are sure we have a well formed json object in $json variable
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if (! $result) {
return false;
}
$json = json_decode(utf8_encode($result));
if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
return false;
}
my solution only works for the next cases:
if you are mistaking a multidimensaional array into a single one
$json = file_get_contents('url_json'); //get the json
$objhigher=json_decode($json); //converts to an object
$objlower = $objhigher[0]; // if the json response its multidimensional this lowers it
echo "<pre>"; //box for code
print_r($objlower); //prints the object with all key and values
echo $objlower->access_token; //prints the variable
i know that the answer was has already been answered but for those who came here looking for something i hope this can help you
When you are using curl sometimes give you 403 (access forbidden)
Solved by adding this line to emulate browser.
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
Hope this help someone.
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'https://www.xxxSite/get_quote/ajaxGetQuoteJSON.jsp?symbol=IRCTC&series=EQ');
//Set the GET method by giving 0 value and for POST set as 1
//curl_setopt($curl_handle, CURLOPT_POST, 0);
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$query = curl_exec($curl_handle);
$data = json_decode($query, true);
curl_close($curl_handle);
//print complete object, just echo the variable not work so you need to use print_r to show the result
echo print_r( $data);
//at first layer
echo $data["tradedDate"];
//Inside the second layer
echo $data["data"][0]["companyName"];
Some time you might get 405, set the method type correctly.
I have a CURL response that looks like this:
{"page_number":2,"items":[],"items_per_page":1,"kind":"search#companies","total_results":0,"start_index":1}
All i need from that is the value of "total_results":0
so I am trying to get "total_results" like this:
$url = "https://api.companieshouse.gov.uk/search/companies?q=POOdfgdfgyygfhfgfgfghgfP&items_per_page=1&start_index=0";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "my_password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$info = curl_getinfo($ch);
curl_close($ch);
echo $output->total_results[0];
However, when I echo the $output->total_results[0];, I get nothing being echoed on my page. So i don't really know what I am doing wrong!
Could someone please advise on this issue?
any help would be appreciated.
What you got as a response is a JSON string. You can parse it to a stdClass object using json_decode:
$object = json_decode( $output );
Then you can access the field you want:
$total_results = $object->total_results;
Alternatively, you can parse the JSON string to an array:
$array = json_decode( $output, true );
and get the var:
$total_results = $array['total_results'];
Does Php have a method that calls a Json URL, and save in a variable the data it fetches
for example can I used:
"https://www.googleapis.com/blogger/v3/blogs/1/posts/"
I been trying with this code, but i am not sure if this is wrking
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/1/posts/");
curl_setopt($ch, CURLOPT_HEADER, 0);
$df = curl_exec($ch);
curl_close($ch);
You can use the bulti-in function json_decode http://php.net/manual/it/function.json-decode.php
$json = file_get_contents("https://www.googleapis.com/blogger/v3/blogs/1/posts/");
$obj = json_decode($json); //returns an object of json values
$array = json_decode($json, true); //returns an array of json values
The problem is http*s*, try adding these:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
I am trying to hit an API and get some JSON back. I can’t seem to figure out what I am doing wrong here. I am getting null as the output.
Here is my PHP code:
<?php
$query_string_full = 'https://api.cityofnewyork.us/calendar/v1/search.htm?app_id=39563317lalaland&app_key=somethingsomething&categories=City%20Government%20Office';
$json = file_get_contents($query_string_full);
$obj = json_decode($json);
echo '<pre>'. json_encode($obj, JSON_PRETTY_PRINT) .'</pre>';
?>
The function file_get_contents doesn’t work with https. You should use the cURL functions instead.
<?php
$query_string_full = 'https://api.cityofnewyork.us/calendar/v1/search.htm?app_id=39563317&app_key=8396021a9bde2aad2eaf8ca9dbeca353&categories=City%20Government%20Office';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $query_string_full);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
$obj = json_decode($json);
echo '<pre>'. json_encode($obj, JSON_PRETTY_PRINT) .'</pre>';
?>
I made this little function to return the json from a few different apis. You need to be using curl.
function exposeJSON ($apiUrl) {
$json_url = $apiUrl;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $json_url);
// Built in authentication if needed.
//curl_setopt($ch, CURLOPT_USERPWD, "$USER:$PASS");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
// grab URL and pass it to the browser
$response = curl_exec($ch);
$return = json_decode($response[0], true);
// close cURL resource, and free up system resources
curl_close($ch);
return $return;
}
So you could do something like
$apiData = exposeJSON('urltoapi');
echo $apiData; // Should be the json.
I tried to use JSON decode to get the youtube API feed. However, when I paste the JSON result in http://www.jsonlint.com/ I noticed something like
"media$group": {
"media$category": [
Unfortunately some symbols are rejected by php. Here is my code, I tried to remove this $ symbol, but maybe not success. How do I solve this?
$url = 'http://gdata.youtube.com/feeds/api/videosq=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) {
...
}
Your problem is the usage of PHP identifiers to access the contents. The simplest solution here would be to get an array instead of an object:
$data = json_decode ( $json , $assoc = true );
This allows access to fields with:
echo $result['media$group']['media$description'];
If you want to keep the object syntax, that's possible with this kludge:
echo $result->{'media$group'}->{'media$category'};
(But arrays are safer here. You don't get a fatal error should the format change and properties be absent.)
This work:
<?php
$url = 'http://gdata.youtube.com/feeds/api/videos?q=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) {
var_dump($result);
}
?>