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

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)

Related

get array content from json (telegram api) in php

I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.

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

Impossible to fetch data from a json file into php variable

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

Get Json Object from external URL with PHP

I have an URL that returns the JSON object below:
{
"addressList": {
"addresses": [
{
"id": 0000000,
"receiverName": "Name Example",
"country": {
"id": "BRA",
"name": "Brasil"
},
"state": {
"id": "SP"
},
"city": "São Paulo",
"zipcode": "00000000",
"type": "Residential",
"street": "000, St Example",
"number": 00,
"neighborhood": "Example",
"hash": "1bf09357",
"defaultAddress": false,
"notReceiver": false
}
]
}
}
I want to get the state value, how can I retrieve that with PHP?
I tried, something like this, but I couldn't get the state value, that should be SP in this case.
$string = '{ "addressList": { "addresses": [ { "id": xxxxxx, "receiverName": "XXXXX XXXXX", "country": { "id": "BRA", "name": "Brasil" }, "state": { "id": "SP" }, "city": "São Paulo", "zipcode": "03164xxx", "type": "Residential", "street": "Rua xxx", "number": xx, "neighborhood": "xxxxx", "hash": "xxxxx", "defaultAddress": false, "notReceiver": false } ] } }';
$json_o = json_decode($string);
$estado = $json_o->state;
How can I achieve the result I want?
Your JSON is not valid - you can validate it on jsonlint.com (it's invalid due to incorrectly formatted numeric values - "id" : 000000).
From then on, you can decode the value and access your data:
$json_o = json_decode($string);
$estado = $json_o->addressList->addresses[0]->state->id;
If you don't have access to the code that generates the JSON, you can attempt to run a regex to match, replace & wrap the numerical values with ":
$valid_json = preg_replace("/\b(\d+)\b/", '"${1}"', $str);
Note: The above is just an example - you'll have to figure out a case where a numerical value is already wrapped by ".
Your JSON has a couple of syntax errors:
"id": 0000000
"number": 00
JSON doesn't support leading zeros. If precise formatting is important, use strings:
"number": "00"
"id": "0000000"
Alternatively, use well-formed integers in the JSON (saves space) and convert them to formatted strings in PHP.
Once you've fixed your JSON, you can access the state->id value of the first address as I do below. When you decode JSON from an untrusted source, be prepared to do some error handling:
$json_string ="..."; //your source, to be decoded
$json_o= json_decode($json_string);
if(is_null($json_o)): //there was an error decoding
$errno = json_last_error();
$err_msg = json_last_error_msg();
die("Json decode failed: Error #$errno: $err_msg");
endif;
//we get here if json_decode succeeded. To get "SP", do...
$stateID = $json_o->addressList->addresses[0]->state->id;
Try:
$json_o = json_decode($string, true);
$estado = $json_o['addressList']['addresses'][0]['state']['id'];

Get JSON value from array in PHP

I have the following JSON
[
{
"part_number": {
"id": "1",
"text": "962-00031-17A004"
},
"categoria": null,
"codigo_cti": "",
"fabricante": null,
"modelo": null,
"numero_serie": "",
"obs": ""
}
]
And I use the code bellow to collect data from it. If I select to extract obs, it works fine. I would like to know how can I collect the text and ID from part_number.
$produtos = json_decode($_POST['produtos'], true);
foreach($produtos as $produto){
echo $produto["obs"]; //WORKS FINE
echo $produto["part_number"]["text"]; //DOES NOT WORK
}
Turn it into an object and not array first - its easier and Object Orientated is the way to go.
Here is a working example;
$json = '[
{
"part_number": {
"id": "1",
"text": "962-00031-17A004"
},
"categoria": null,
"codigo_cti": "",
"fabricante": null,
"modelo": null,
"numero_serie": "",
"obs": ""
}
]';
$produtos = json_decode($json, false);
foreach($produtos as $produto){
echo $produto->part_number->id;
}

Categories