Get JSON value from array in PHP - 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;
}

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

Parsing JSON - getting null output - PHP

My code:
$json_response = json_decode($response, true);
$tag= $json_response['results']['tags'][0]['tag'];
print $tag;
My JSON:
{
"results": [
{
"tagging_id": null,
"image": "image.jpg",
"tags": [
{
"confidence": 100,
"tag": "herb"
},
{
"confidence": 98.3637619018555,
"tag": "plant"
}
]
}
]
}
I am trying to output "herb". I have looked up through examples but cannot figure out where the bug is.
I am reading results and then the trees.
You have to fetch the first element inside ['results'].
echo $json_response['results'][0]['tags'][0]['tag'];

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

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)

how to loop through a Json responce

I have web page which get Json responce like this
{
'hotel_1page':[
{
'id':'10',
'name':'fsf',
'telephone':'233333'
},
{
'id':'11',
'name':'setttttt',
'telephone':'213123123'
},
{
'id':'12',
'name':'fsdfsdf',
'telephone':'122212121'
},
{
'id':'13',
'name':'xxcvcxv',
'telephone':'2147483647'
},
{
'id':'14',
'name':'dssdfg',
'telephone':'2147483647'
},
{
'id':'15',
'name':'dfsdfsdf',
'telephone':'21312321'
},
{
'id':'16',
'name':'fx_test_nw1',
'telephone':'23232323'
},
{
'id':'17',
'name':'fx_test_nw2',
'telephone':'31313131'
}
]
}
and i want to loop through this data and get this data to array and display as html how can i achieve this
this is where i get get json responce,and when i var_dump json encoded variable it says null,where $json variable shows the json responce,
$json = file_get_contents('http://www.example.com/hotel_list.php');
var_dump($json);
$array = json_decode($json, true);
var_dump($array);
The json that you are trying to parse is invalid. Change the single quotes to double quotes and you should be able to parse it to an array.
The JSON documentation says
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
This should work:
$json = '{ "hotel_1page": [ { "id": "10", "name": "fsf", "telephone": "233333" }, { "id": "11", "name": "setttttt", "telephone": "213123123" }, { "id": "12", "name": "fsdfsdf", "telephone": "122212121" }, { "id": "13", "name": "xxcvcxv", "telephone": "2147483647" }, { "id": "14", "name": "dssdfg", "telephone": "2147483647" }, { "id": "15", "name": "dfsdfsdf", "telephone": "21312321" }, { "id": "16", "name": "fx_test_nw1", "telephone": "23232323" }, { "id": "17", "name": "fx_test_nw2", "telephone": "31313131" } ] }';
echo '<pre>';
var_dump(json_decode($json, true));
echo '</pre>';
I replaced all single quotes with double quotes, that did the trick.
I used single quotes before which caused json_decode to return null
[Edit for usage]
To use the data, you could use something like this:
$obj = json_decode($json, true);
foreach($obj as $row)
{
foreach($row as $key => $item)
{
// $item['id']
// $item['name']
// $item['telephone']
}
}
I'm using a nested foreach() because the id, name and telephone are an array within the hotel_page1 array

Categories