I need some help accessing an api. http://market.huobi.com/staticmarket/detail.html
in PHP.
$json = file_get_contents("http://market.huobi.com/staticmarket/detail.html");
$obj = json_decode($json);
Below is a small sample of the api response.
$obj =
{
"sells": [
{
"price": 3840,
"level": 0,
"amount": 1
},
{
"price": "3840.05",
"level": 0,
"amount": 0.287
},
{
"price": 3841,
"level": 0,
"amount": 0.1
} ],
"p_new": 3838,
"level": -72.12,
"amount": 82792,
"total": 321774060.34653,
"amp": -2,
"p_open": 3910.12,
"p_high": 3925,
"p_low": 3809.99,
"p_last": 3910.12
}
echo "Ask " . $obj->sells[0]->price; // does not work
echo "Volume" . $obj->amount;// does not work
Help will be appreciated.
The API you're calling is returning JSONP data, not JSON data.
JSONP data looks like:
somefunction(JSONdata)
You need to remove the function call wrapper.
$jsonp = file_get_contents("http://market.huobi.com/staticmarket/detail.html");
preg_match('/^.*?\((.*)\)/s', $jsonp, $match);
$json = $match[1];
$obj = json_decode($json);
echo "Ask " . $obj->sells[0]->price . '<br>';
echo "Volume " . $obj->amount;
Related
This is my php file code where i am fetching data from thecatapi
i needed the specific format for datatable
$xml=file_get_contents('https://thecatapi.com/api/images/get?format=xml&results_per_page=3');
$xml = new SimpleXMLElement($xml);
$datas=array();
$datas['rows'] = $xml->data->images;
echo json_encode($datas, true);
Output is:
{"total":50,
"rows":{"image":[
{"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
"id":"e0i",
"source_url":"http:\/\/thecatapi.com\/?id=e0i"
},
{"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
"id":"MTYwNDE0MQ",
"source_url":"http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
},{
"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
"id":"bon",
"source_url":"http:\/\/thecatapi.com\/?id=bon"
}
]
}
}
but i wanted in this json form
{
"total": 800,
"rows": [
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
Just came up with an alternativ solution. Change this line:
$datas['rows'] = $xml->data->images;
to this:
$datas['rows'] = $xml->data->images->image;
otherwise you can still do this
Decode the json string into an object and modify it suit your needs.
$stdClassObject = json_decode($jsonData);
$stdClassObject->rows = $stdClassObject->rows->image;
$newJsonData = json_encode($stdClassObject, JSON_PRETTY_PRINT);
echo '<pre>';
print_r($newJsonData);
echo '</pre>';
New output:
{
"total": 50,
"rows": [
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
"id": "e0i",
"source_url": "http:\/\/thecatapi.com\/?id=e0i"
},
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
"id": "MTYwNDE0MQ",
"source_url": "http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
},
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
"id": "bon",
"source_url": "http:\/\/thecatapi.com\/?id=bon"
}
]
}
Okay so bascially I have this structure as JSon from an API:
{
"tag": "8L9L9GL",
"name": "Jo͛hͥn̽",
"trophies": 5338,
"rank": 291,
"arena": {
"name": "Master II",
"arena": "League 5",
"arenaID": 17,
"trophyLimit": 5200
},
"clan": {
"tag": "2U2GGQJ",
"name": "Reddit Bravo",
"role": "coLeader",
"donations": 0,
"donationsReceived": 0,
"donationsDelta": 0,
"badge": {
"name": "A_Char_Rocket_02",
"category": "03_Royale",
"id": 16000167,
"image": "https://cr-api.github.io/cr-api-assets/badges/A_Char_Rocket_02.png"
}
},
I'm trying to get the Clan -> Name but it isn't working with this code in PHP:
echo "<p style='font-size:75;'>".$json->clan['name']."</p>";
How could I make it work?
Try this:
$json->clan->name
<?php
$json = '{
"tag": "8L9L9GL",
"name": "Jo͛hͥn̽",
"trophies": 5338,
"rank": 291,
"arena": {
"name": "Master II",
"arena": "League 5",
"arenaID": 17,
"trophyLimit": 5200
},
"clan": {
"tag": "2U2GGQJ",
"name": "Reddit Bravo",
"role": "coLeader",
"donations": 0,
"donationsReceived": 0,
"donationsDelta": 0,
"badge": {
"name": "A_Char_Rocket_02",
"category": "03_Royale",
"id": 16000167,
"image": "https://cr-api.github.io/cr-api-assets/badges/A_Char_Rocket_02.png"
}
}
}';
$json = json_decode($json);
echo $json->clan->name;
// Reddit Bravo
If you want to use $json['clan']['name']; then you have to set the assoc param like:
$json = json_decode($json, true);
echo $json['clan']['name'];
// Reddit Bravo
Depending on your particular call to json_decode(), if you've used...
$json = json_decode($jsonData,true);
then use
echo "<p style='font-size:75;'>".$json['clan']['name']."</p>";
Else if you've used...
$json = json_decode($jsonData);
then use
echo "<p style='font-size:75;'>".$json->clan->name."</p>";
If using the first call, then you create an associative array and so use array access method. If you don't pass true as the second parameter, this creates the structure as objects and so use the second method of access.
You will have to json_decode the same and use it.
Following is the piece of code
echo json_decode($json)->clan->name;
Stitch it into your HTML as
echo "<p style='font-size:75;'>".json_decode($json)->clan->name."</p>";
Tested this snippet. Should work for you too.
am having issues trying to get contents of this json, am using php.
{"song":{"returncode":"200","returnmsg":"OK","title":"Despacito Ft. Justin Bieber","artist":"Luis Fonsi, Daddy Yankee","album":"","size":"9193600","url":"http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3","time":"1499079781","date":"Jul 3, 2017","source":"","active":"1","albumart":"https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg","speed":"21","counter":"850850"}
this is my function, that returns the json
public function getSong($id) {
$song_url = 'http://databrainz.com/api/data_api_new.cgi?jsoncallback=&id='.$id.'&r=mpl&format=json&_=';
$api = Api::getSpotOn($song_url);
$song = $api->{'song'};
return $song;
}
I want to get all it content.
Thanks!
In the json example you provided a final '}' is missing and the json_decode will return Null without it as it's non a valid json.
But, since you have the getSong method the following should work:
$retObject = json_decode(getSong($songId));
$song = $retObject->song;
print_r($song);
echo 'returncode:'.$song->returncode.'<br/>';
echo 'returnmsg:'.$song->returnmsg.'<br/>';
echo 'title:'.$song->title.'<br/>';
echo 'artist:'.$song->artist.'<br/>';
echo 'album:'.$song->album.'<br/>';
echo 'size:'.$song->size.'<br/>';
echo 'url:'.$song->url.'<br/>';
echo 'time:'.$song->time.'<br/>';
echo 'date:'.$song->date.'<br/>';
echo 'source:'.$song->source.'<br/>';
echo 'active:'.$song->active.'<br/>';
echo 'albumart:'.$song->albumart.'<br/>';
echo 'speed:'.$song->speed.'<br/>';
echo 'counter:'.$song->counter.'<br/>';
try the following:
$result = json_decode(
'{
"song": {
"returncode": "200",
"returnmsg": "OK",
"title": "Despacito Ft. Justin Bieber",
"artist": "Luis Fonsi, Daddy Yankee",
"album": "",
"size": "9193600",
"url": "http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3",
"time": "1499079781",
"date": "Jul 3, 2017",
"source": "",
"active": "1",
"albumart": "https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg",
"speed": "21",
"counter": "850850"
}
}'
);
var_dump($result);
echo $result->song->title;
I'm using Giscloud's REST API to grab a json with some info that i need for my web app. The problem is that it seems impossible that I can fetch and/or decode any data from that json using the corresponding php functions. I think it has something to do with the way the json file is structured.
This is the json file (some fields edited):
{
"type": "maps",
"total": 3,
"page": 1,
"data": [
{
"id": "edited",
"name": "Mapa de Mantención en Linea",
"owner": "edited",
"epsg": "900913",
"active": "1",
"copyright": "",
"proj4": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs",
"units": "meter",
"maxzoom": "0",
"mobileacess": "f",
"bgcolor": "#417893",
"wmsaccess": null,
"modified": 1483563460,
"accessed": 1483563460,
"created": 1483021672,
"description": "",
"maptype": null,
"assets": null,
"rating": "0",
"units_proj4": "meter",
"visited": "31",
"resource_id": "6102219",
"measure_unit": "meter",
"share": "f",
"bounds": " {\"xmin\":-8027875.3326789,\"xmax\":-7742459.4690621,\"ymin\":-4065685.5344885,\"ymax\":-3929474.7500843}"
},
{
"id": "edited",
"name": "Mapa de Operaciones",
"owner": "edited",
"epsg": "900913",
"active": "1",
"copyright": "",
"proj4": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs",
"units": "meter",
"maxzoom": "0",
"mobileacess": "f",
"bgcolor": "#417893",
"wmsaccess": null,
"modified": 1483563473,
"accessed": 1483563473,
"created": 1483021672,
"description": "",
"maptype": null,
"assets": null,
"rating": "0",
"units_proj4": "meter",
"visited": "45",
"resource_id": "6102603",
"measure_unit": "meter",
"share": "f",
"bounds": "{\"xmin\":-8027263.8364526,\"xmax\":-7741847.9728358,\"ymin\":-4075469.474109,\"ymax\":-3939258.6897048}"
},
{
"id": "edited",
"name": "Mapa M&IC",
"owner": "edited",
"epsg": "900913",
"active": "1",
"copyright": "",
"proj4": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs",
"units": "meter",
"maxzoom": "0",
"mobileacess": "f",
"bgcolor": "#417893",
"wmsaccess": null,
"modified": 1483563449,
"accessed": 1483563449,
"created": 1483021672,
"description": "",
"maptype": null,
"assets": null,
"rating": "0",
"units_proj4": "meter",
"visited": "35",
"resource_id": "6102604",
"measure_unit": "meter",
"share": "f",
"bounds": "{\"xmin\":-8028181.080792,\"xmax\":-7742765.2171752,\"ymin\":-4074552.2297696,\"ymax\":-3938341.4453654}"
}
]
}
These are the different ways that i've tried to decode this json and put it into a variable.
$json = curl_exec($ch);
// Number 1
$data = var_dump(json_decode($json));
echo $data['data'][0]['id'];
exit;
// Number 1 returns
object(stdClass)[21]
public 'code' => string 'FATAL' (length=5)
public 'msg' => string 'Internal error' (length=14)
// Number 2
$data = json_decode($json,true);
echo $data['data'][0]['id'];
// Number 2 returns
PHP Undefined index: data
I've tried several other similar functions, like print_r. Or change some values there and here, but nothing has worked.
I would appreciate a lot some help on this!
Some extra info:
There's no problem with curl. It executes correctly.
Yes, the server answers with a json file.
UPDATE
Using json_last_error() (no need of parameters) I was able to debbug. The function returns an int depending of the type of error. Mine was 0meaning that there's no error.
I think I ran out of ideas for this.
Loose the var_dump() thats just for debugging and it is stoppping the json_decode() from returning a PHP Object from the json_decode().
Then use the correct object syntax to address the object
$json = curl_exec($ch);
$data = json_decode($json);
// debug code
if ( json_last_error() > 0) {
echo json_last_error_msg();
} else
// this should print the data structure
print_r($data);
}
// end debug code
echo $data->data[0]->id;
If you want all the id's from all the occurances you can do
$json = curl_exec($ch);
$data = json_decode($json);
foreach ($data->data as $idx => $obj ){
echo "Occurance $idx = " . $obj->id;
}
Object syntax:
$json = curl_exec($ch);
$json_data = json_decode($json);
foreach ( $json_data->data as $data_item){
echo '<p>ID: ' . $data_item->id . ' -- Name: ' . $data_item->name . '</p>';
}
Array Syntax:
Get the data as an associated array by adding a second parameter TRUE to json_decode() php docs
$json = curl_exec($ch);
$data_array = json_decode($json, true);
foreach ( $data_array['data'] as $item){
echo '<p>ID: ' . $item['id'] . ' -- Name: ' . $item['name'] . '</p>';
}
i dont preferable to use cURL In this situation , you can use
file_get_contents
so here is a simple code
$userdata = json_decode(file_get_contents("JSON_URL_GOES_HERE"), true)
$u_ID = $userdata['data'][0]['id'];
and so on
see :file_get_contents
I am getting a problem in generating values of a JSON string into a dropdown menu.I have a JSON API
http://service.proventustechnologies.com/api/json?username=demo&token=4ce26206-025d-11dc-8314-0800200c9a66&method=getattributevalues&dimensionId=10
When you click it you will see many values like this.
{
"response": {
"id": 10,
"values": [
{
"id": 258,
"value": "Cameras"
},
{
"id": 2581,
"value": "GPS Navigation"
},
{
"id": 259,
"value": "MP3 Players"
},
{
"id": 260,
"value": "Cell Phone/PDA"
},
{
"id": 6377,
"value": "Digital Photo Frame"
},
{
"id": 110,
"value": "Motherboard"
},
{
"id": 108,
"value": "Desktop/Server"
},
{
"id": 109,
"value": "Notebook"
},
{
"id": 10738,
"value": "E-Book Reader"
}
],
"name": "System Type"
},
"status": "ok"
}
I want to print all the values such as Cameras,GPS Navigation in a dropdown menu.Thank you for any kind of help.
Use json_decode to convert json encoded string into PHP variable:
<?php
$json = file_get_contents($your_url);
$obj = json_decode($json);
echo $obj->response->id; // prints 10 (based on your sample code)
?>
I can't really get a feel for what your level of knowledge is, but you should load your data in a html select element for example like this:
<?php
echo '<select>';
$jsonData = file_get_contents($url);
$jsonDataObject = json_decode($jsonData);
foreach($jsonDataObject->response->values as $option){
echo '<option value=' . $option->id . '>' . $option->value . '</option>';
}
echo '</select>';
?>
hridaynehu,
Its very easy to populate the select box using your json array values. Follow below line of code.
<?php
$url = 'http://service.proventustechnologies.com/api/json?username=demo&token=4ce26206-025d-11dc-8314-0800200c9a66&method=getattributevalues&dimensionId=10';
$content = file_get_contents($url);
$jsonArray = json_decode($content, true);?>
<select name="json_populate"><?php
foreach($jsonArray->response->values as $jsonValue) { ?>
<option value="<?php echo $jsonValue->id; ?>"><?php echo $jsonValue->value; ?></option>
<?php } ?>
</select>
Please mark it answer if it helps you. Because it may help others too.
With Thanks & Regards,
Sanjoy Dey