Impossible to fetch data from a json file into php variable - php

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

Related

Getting data from nested arrays in json with php

I have my json from a url feed. Here's a sample below. I'm not doing the foreach loop correctly is the problem
{
"useLive": true,
"models": [
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"id": 5293074,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu7",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model1",
"languages": ["en"],
"stripScore": 998.5,
"token": "93021860dbebd5ba27e604f6b4b93754"
},
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"id": 6492104,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu8",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model2",
"languages": [],
"stripScore": 997.25,
"token": "2c6ee95270f6faf76cd33321732136e3"
}
],
"ttl": 15,
"tagType": "F+T",
"tagName": "Featured",
"defaultTags": [
{
"name": "whatever1",
"url": "/tags/whatever1"
},
{
"name": "whatever2",
"url": "/tags/whatever2"
},
{
"name": "whatever3",
"url": "/tags/whatever3"
}
],
"serverTime": "2018-09-26T14:23:00Z"
}
Here's my php code so far. I've tried quite a few different things. I normally use xml feeds which seem to be easy for me to setup for what I need. I'm not sure what I'm missing here.
$url = 'https://whatever.com/api/external/v4/widget?userId=whatever&tag=featured'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$performers = json_decode($data, true); // decode the JSON feed
foreach ($performers as $performer) {
$info = $performer[0]["username"];
echo $info;
}
I'm only getting the first username and then error messages.
Warning: Illegal string offset 'username' in /whatever
Can anyone help with this?
You should use $performers['models'] array in foreach and then get username it will work fine try the following code
$performers = json_decode($data, true);
if(isset($performers['models'])){
foreach ($performers['models'] as $performer) {
$info = (isset($performer["username"])) ? $performer["username"] : '';
echo $info;
echo "<br>";
}
}
Output
model1
model2

php decode JSON can't get a value inside an array

I'm trying to get thumbnail_url form the following JSON
{
"uuid": "00012710-4b65-0131-ffe6-22000a499ea4",
"camera_uuid": "98373a20-79ee-0130-3e42-1231390fcc11",
"created_at": "2013-12-20T05:25:02.000Z",
"percent_complete": 100,
"short_code": "KKtB4Q",
"metadata": {
},
"state": "published",
"recorded_from": "http://singwho.com",
"publish_type": null,
"formats": [
{
"name": "720p",
"width": 1280,
"height": 720,
"video_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/mp4.mp4",
"flv_url": null,
"flv_stream": null,
"mp4_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/mp4.mp4",
"mp4_stream": "rtmp://sa0xpxq1vz1ri.cloudfront.net/cfx/st&mp4:98373a20-79ee-0130-3e42-1231390fcc11/00012710-4b65-0131-ffe6-22000a499ea4_720p.mp4?Expires=1436913071&Signature=NppwMddejKbM2JMYrjsUUC5TJN0YfbgOox6sBKwO1YcftAaspf25ByG8drEG4zM-pTD6mST71YtBb3pQ5JzhHM33B6JQv0BsZvjGHarA7kVq9b6GG27wY5N5F6Sy79l5GNO3k9-Sh4MRy6fABZEDQUxd8TZ1HD7Usj2FlPYXxWXZmWQlo~43YKRnium7dcEzh-RRXbXfNQarfz1ju~OXI4J9ug1DRmHVtqV0F32cEDdCSCVy5Tyokf7IgO5SXATkuIkRtt52TdInFXmWmLbGfopDtKgua8NZXPaDbK35ra7AX2DuQE3iKTeX5oCWgVCPCAUz1PenLtK8rOYhTyYgJg__&Key-Pair-Id=APKAIYEVFIMHKY7YWGKA",
"webm_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/webm.webm",
"webm_stream": "rtmp://sa0xpxq1vz1ri.cloudfront.net/cfx/st&webm:98373a20-79ee-0130-3e42-1231390fcc11/00012710-4b65-0131-ffe6-22000a499ea4_720p.webm?Expires=1436913071&Signature=Qc-gjpwSHp3QmXzoiLuAMy11ReUHyLvRuuaszBYRT~GEzp~wl-TTZ-sGqo-XBlJlxH-54LmzXPryygS8ZCwdQQs0~5le69YXlL8RONl7kaLwmLSKlSE0PJlGzJoUW8kqO1mZxIfvrcmpYPdpCukm5J6eTv2U0rWCzAGfAeSiT7kUUc-9uGxLjjeOLIXVKebyYYhjT3wC-Gp5jd4ODCq3JB-IAWpOCOcXxF7oCuF-ag5WznaAeasW200M4yuYHvuDmu~dz~r52NcykeldzQ9Wq4laRuxaLRYaGZpB3y7og31RoWo75bomoT2vOO2rO-4~pz1tcfoYsg05T14er62KOA__&Key-Pair-Id=APKAIYEVFIMHKY7YWGKA",
"thumbnail_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/thumb.png",
"small_thumbnail_url": "https://cameratag.com/videos/00012710-4b65-0131-ffe6-22000a499ea4/720p/small_thumb.png",
"state": "COMPLETED",
"completed_at": "2013-12-20T05:30:12.000Z",
"length": 195
}
],
"plays": 0
}
This is how decode the JSON, I'm able to get 'uuid'
$raw = file_get_contents('php://input');
$json = json_decode($raw, true);
I tried with
foreach ($json->formats as $format) {
$url = $format["thumbnail_url"];
}
and
$url = $json->formats[0]->thumbnail_url
and
$url = $json['formats']['thumbnail_url']
but I'm still unnable to get the right value. I'm I missing something?
You just about had its $url = $json['formats'][0]['thumbnail_url']
$json is a nested array. $json['formats'] is an array of objects, to get the first object use $json['formats'][0]
You can easily see what is in $json with var_export($json) or print_r($json)

json_decode does not return array in php

I am facing with a problem, when I am trying to parse json returns from server into array in php. Here is my code ...
<?php
mb_internal_encoding('UTF-8');
$url = 'http://localhost/busexpress/api/v1/mobile_user_register/mobile_user_register/retrieve.json';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
//$data="'".$data."'";
echo $data;
curl_close($ch);
//$trimspace = preg_replace('/\s+/', '', $data);
//echo $trimspace;
$jdata = json_decode($data, true);
print_r $jdata;
?>
This is the json after trimming space. I also want to convert it int array with json_decode() but no result return. I think this json is valid. And suggestion pls. This is my firstly trying to feed web service from server.
Thanks
'{
"status": "1",
"user": [
{
"id": "27",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "0d08ed",
"deposit": "0",
"created": "2015-06-0316:35:08",
"updated": "1110-11-3000:00:00",
"status": "0"
},
{
"id": "28",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "fb4876",
"deposit": "0",
"created": "2015-06-0316:37:14",
"updated": "1000-01-0100:00:00",
"status": "0"
}
]
}'
----------Edit---------
As your suggestion I comment trimming space and correct json format. And echo $data; .....
{
"status": "1",
"user": [
{
"id": "27",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "0d08ed",
"deposit": "0",
"created": "2015-06-0316:35:08",
"updated": "1110-11-3000:00:00",
"status": "0"
},
{
"id": "28",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "fb4876",
"deposit": "0",
"created": "2015-06-0316:37:14",
"updated": "1000-01-0100:00:00",
"status": "0"
}
]
}
In decoding array doesn't have any data.
$jdata = json_decode($data, true);
print_r $jdata;
echo "user status -> ". $jdata["status"];
when I copy that json and hard code in a string, decode it again, it works for me. please see my testing code....
$data =' {"status":"1","mobile_user":[{"id":"1","name":"saa","phone_no":"09978784963","activate_code":"","deposit":"0","created":"2015-05-29 00:00:00","updated":"0000-00-00 00:00:00","status":"1"},{"id":"3","name":"ttr","phone_no":"090930499","activate_code":"","deposit":"0","created":"2015-06-01 00:00:00","updated":"0000-00-00 00:00:00","status":"0"}]}';
$data = json_decode($data,true);
$status = $data['status'];
$mobile_user = $data['mobile_user'];
$id = $mobile_user[0]["id"];
$name = $mobile_user[0]["name"];
echo "id -> ". $id ."<br>";
echo "name -> ". $name;
Any suggestion pls!
I think your json is malformed. Remove $data="'".$data."'";
You can check json error if any.
And $trimspace = preg_replace('/\s+/', '', $data); is needless.
json_decode usually returns an object, so I don't think your code is wrong here.
$arrayObject = new ArrayObject($object);
$array = $arrayObject->getArrayCopy();
This is how you can convert it to an array. It works in PHP 5.3+
Try this
$jdata = json_decode($trimspace, true);
print_r($jdata);
First of all your json is malformed. Remove the '' from the beginning and the end of your file. The contents of $data should look like this:
{
"status": "1",
"user": [
{
"id": "27",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "0d08ed",
"deposit": "0",
"created": "2015-06-0316:35:08",
"updated": "1110-11-3000:00:00",
"status": "0"
},
{
"id": "28",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "fb4876",
"deposit": "0",
"created": "2015-06-0316:37:14",
"updated": "1000-01-0100:00:00",
"status": "0"
}
]
}
Second $jdata is an associative array. You cannot print its contents with echo. Instead do
print_r($jdata);
Third you don't need to remove spaces. Do that in the script that produces the json, otherwise just parse the json with the spaces directly.

Cant get value from JSON

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;

Accessing the Returned Data from an API Call

I am accessing data via an API using cURL. The returned result is JSON. I am trying to access parts of the returned data to display relevant information to the user. Here is a sample of what is being returned:
[{
"FirstName": "Person1",
"LastName": "Guy",
"SISId": "7",
"MiddleName": "",
"EmailAddress": "demo#yahoo.com",
"FederalId": "",
"StateId": "",
"ActiviationDate": "\/Date(1375751488440)\/",
"ExpirationDate": null,
"Status": 1,
"UserId": 5632414,
"MembershipId": 5632414,
"Role": 5,
"IsOnline": false,
"HasUnreadMessages": false,
"LastLoginDate": null,
"LastActivityDate": null
}, {
"FirstName": "Person2",
"LastName": "Girl",
"SISId": "18",
"MiddleName": "Bailey",
"EmailAddress": "superstar08_03#yahoo.com",
"FederalId": "",
"StateId": "",
"ActiviationDate": "\/Date(1376928013777)\/",
"ExpirationDate": null,
"Status": 1,
"UserId": 5932535,
"MembershipId": 5932535,
"Role": 5,
"IsOnline": false,
"HasUnreadMessages": false,
"LastLoginDate": null,
"LastActivityDate": null
}]
I have tried several different methods using PHP to try and access the UserId data but have not been successful. Here is my most current code:
<?php
//API CALL IS MADE ABOVE THIS LINE
$ch = curl_init();
curl_setopt_array($ch, $options);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
if ($output === false || $info['http_code'] != 200) {
$output = "No cURL data returned [" . $info['http_code'] . "]";
if (curl_error($ch)) {
$output .= "\n" . curl_error($ch);
}
}
$object = json_decode($output);
print $obj->{'FirstName'}; // Person1
?>
$object is an array.
If you want person one:
echo $object[0]->FirstName;

Categories