I'm attempting to insert all results from a JSON API result, they have put a limit on max 200 results per page, although they provide the next url to be accessed to get the next 200 results, here's an example of the result that the API provides.
{
"count": 200,
"total": 31108,
"nextUrl": "https://**/api/v1/***/orders?secure_auth_key=****&offset=200",
"orders": [
{
"number": 40026,
"paymentStatus": "ACCEPTED",
etc....
}
],
}
Here is my current code to grab these 200 results and store them in mySQL
$url = "https://****/api/v1/***/orders?secure_auth_key=*****";
$json = file_get_contents($url, 0, null, null);
$result = json_decode($json, true)
foreach($result['orders'] as $order) {
mysql_query("INSERT INTO blah blah");
}
How can i create it so it automatically gets the data from the next page e.g : offset=200 and add all the data to database like i did in the first results.
With the assumption that if there is no more results they don't provide a URL for the next 200, why not just use that as a check.
eg. after your save simple if to check if the last result had a nexturl?
if(isset($result['nextUrl'])){
$url = $result['nextUrl'];
$json = file_get_contents($url, 0, null, null);
$result = json_decode($json, true)
foreach($result['orders'] as $order) {
mysql_query("INSERT INTO blah blah");
}
}
Ideally move that into a function you can continually call where needed...
Related
I'm trying to decode JSON format
My API Endpoint is https://api.reliableserver.host/api/landings
And this is the output
{
"success": true,
"data": [
{
"id": 1,
"primary_balance": "$4,184.37",
"primary_currency": "USD",
"secondary_balance": "¥0",
"secondary_currency": "JPY",
"tertiary_balance": "฿0.00",
"tertiary_currency": "THB",
"first_language": "ไทย",
"second_language": "English",
"footer_text": "a",
"created_at": "2020-10-26T07:45:49.000000Z",
"updated_at": "2020-10-28T05:31:04.000000Z",
"deleted_at": null
}
],
"message": "Landings retrieved successfully"
}
I need to echo individual values, for example: Primary Balance: $4,184.37
I tried using this:
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode($url);
echo $obj>primary_balance;
But it didnt work, kindly guide me what am I doing wrong.
You can do this way :
$url = '{"success": true,"data": [{"id": 1,"primary_balance": "$4,184.37","primary_currency": "USD","secondary_balance": "¥0","secondary_currency": "JPY","tertiary_balance": "฿0.00","tertiary_currency": "THB","first_language": "ไทย","second_language": "English","footer_text": "a","created_at": "2020-10-26T07:45:49.000000Z","updated_at": "2020-10-28T05:31:04.000000Z","deleted_at": null}],"message": "Landings retrieved successfully"}';
$obj = json_decode($url, true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Above code tested here
You need file_get_contents() method to get the JSON data from your given URL.
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode(file_get_contents($url), true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Basically, you are not calling that api anywhere. If it is an open endpoint (without auth or headers, you can do file_get_contents() or I suggest you to use curl.
Also, you need to check on response data structure, it has a 'data' key which is an array. so you need to use foreach to iterate on the 'data' key.
I have given a sample answer that should work if there is only 1 item in data.
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp);// will return in object form
echo $obj->data[0]->primary_balance;
or
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp, true); // will return in array form
echo $obj['data'][0]['primary_balance'];
json_decode()
I want to get price of btc to usd using coinmarketcap's API.
$response = curl_exec($curl); // Send the request, save the response
$type = json_decode($response,true);
Getting 200 Ok response
"data": {
"symbol": "BTC",
"id": "1",
"name": "Bitcoin",
"amount": 50,
"last_updated": "2018-06-06T08:04:36.000Z",
"quote": {
"USD": {
"price": 284656.08465608465,
"last_updated": "2018-06-06T06:00:00.000Z"
},
I want to get Price value from usd but its not working when i tried
$examount = $type->USD->price;
Since you are using
$response = curl_exec($curl); // Send the request, save the response
$type = json_decode($response,true);
It means that your object is converted to associative array,
to access the price use:
$type['data']['quote']['USD']['price'];
You should be good to go.
Edit
In case $type contains more than one element, you will need to loop them.
foreach($type['data'] as $singleQuote){
$price = $singleQuote['quote']['USD']['price'];
echo 'Quote for: '.$singleQuote['symbol'].' in USD: '.$price.'<br/>';
}
Because you are passing 2nd param true that will convert it to associative array:
$response = curl_exec($curl); // Send the request, save the response
$type = json_decode($response,true);
$examount = $type['data']['quote']['USD']['price'];
I hope above will solve your problem as per the documentation of coinmarketcap (https://coinmarketcap.com/api/documentation/v1/#section/Endpoint-Overview)
the problem was cuased by the $request was returning null all of above are correct also
As Facebook changed their API and deprecated the old one, I need to get data (likes count, share count, comment count) about single pages.
I figured out how to get data over Facebook graph (example link):
https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9
But now I don't know how to echo single data (likes count) in php. I tried with json, but had no sucsess:
$json = file_get_contents($xml);
$json_output = json_decode($json);
Any suggestions how to make this work?
The API Explorer adds the Access Token automatically, but you have to add it manually in your URL:
https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9&access_token=xxx
Result:
{
"http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9": {
"og_object": {
"likes": {
"data": [
],
"summary": {
"total_count": 0,
"can_like": true,
"has_liked": false
}
},
"id": "949055545223224"
},
"share": {
"comment_count": 0,
"share_count": 346
},
"id": "http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9"
}
}
The results of json_decode() are Objects.
So you can easily browse through like this:
<?php
$url = 'https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9';
$json = file_get_contents($url);
$json_output = json_decode($json);
foreach( $json_output as $site=>$data ){
echo $site."\n";
echo $data->og_object->likes->summary->total_count;
}
?>
I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.
Take this json response:
{
"self":"http://macpro.local:2990/jira/rest/api/2/issue/CSS-4/votes",
"votes":2,
"hasVoted":true,
"voters":[
{
"self":"http://macpro.local:2990/jira/rest/api/2/user?username=admin",
"name":"admin",
"avatarUrls":{
"16x16":"http://macpro.local:2990/jira/secure/useravatar?size=small&avatarId=10062",
"48x48":"http://macpro.local:2990/jira/secure/useravatar?avatarId=10062"
},
"displayName":"admin",
"active":true
},
{
"self":"http://macpro.local:2990/jira/rest/api/2/user?username=timn_1",
"name":"timn_1",
"avatarUrls":{
"16x16":"http://macpro.local:2990/jira/secure/useravatar?size=small&avatarId=10062",
"48x48":"http://macpro.local:2990/jira/secure/useravatar?avatarId=10062"
},
"displayName":"User Two",
"active":true
}
]
}
I'm at a loss for how to get the avatarUrls->16x16 from above. I've been getting everything else pretty easily with commands like:
$decoded = json_decode($result);
$decoded->votes; //returns # of votes
$decoded->voters->name; //returns the name
But how do I get the 16x16 value? I get an error if I try this:
$decoded->voters->avatarUrls->16x16;
Same as always.
$decoded->voters->avatarUrls->{'16x16'}
You can also do
$decoded = json_decode($result, true);
$decoded['voters']['avatarUrls']['16x16'];
if you like the Array style better.