Looping through JSON using PHP [duplicate] - php

This question already has answers here:
PHP 7 array columns not working for multidimensional array
(1 answer)
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
I have the below JSON I need to loop through in PHP.
{
"page": 1,
"perPage": 3,
"count": 607,
"status": "OK",
"tickers": [
{
"ticker": "A",
"name": "Agilent Technologies Inc.",
"market": "STOCKS",
"locale": "US",
"type": "CS",
"currency": "USD",
"active": true,
"primaryExch": "NYE",
"updated": "2020-12-15",
"codes": {
"cik": "0001090872",
"figiuid": "EQ0087231700001000",
"scfigi": "BBG001SCTQY4",
"cfigi": "BBG000C2V3D6",
"figi": "BBG000C2V3D6"
},
"url": ""
},
{
"ticker": "AA",
"name": "Alcoa Corporation",
"market": "STOCKS",
"locale": "US",
"type": "CS",
"currency": "USD",
"active": true,
"primaryExch": "NYE",
"updated": "2020-12-15",
"codes": {
"cik": "0001675149",
"figiuid": "EQ0000000045469815",
"scfigi": "BBG00B3T3HF1",
"cfigi": "BBG00B3T3HD3",
"figi": "BBG00B3T3HD3"
},
"url": ""
},
{
"ticker": "WADV",
"name": "Wireless Advantage Inc Common Stock",
"market": "STOCKS",
"locale": "US",
"type": "CS",
"currency": "USD",
"active": true,
"primaryExch": "GREY",
"updated": "2020-03-30",
"codes": {
"figiuid": "EQ0010295500001000",
"scfigi": "BBG001S87270",
"cfigi": "BBG000DKG4K2",
"figi": "BBG000DKG4K2"
},
"url": ""
}
]
}
This is my function to loop through - I simply only need the "ticker" from each of the nested arrays.
public function getTickers()
{
$APIKey = "API_KEY";
$tickers_request = 'API_URL';
$session = curl_init($tickers_request);
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);
$json = substr($response, strpos($response, "{"));
$result = json_decode($json, true);
$ticker =[];
foreach($result as $results)
{
foreach ($results['tickers'] as $ticker)
{
$ticker['ticker'] = $results['ticker'];
}
}
return $ticker;
}
I receive these two errors in PHP -
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Severity: Notice
Message: Array to string conversion
What's wrong with my function? I'm a seasoned PHP developer but perhaps I am missing something...

Your code doesn't make sense. First you don't need the first foreach. All you need is
$result = json_decode($json, true);
$tickers =[];
foreach ($result['tickers'] as $results)
{
$tickers[] = $results['ticker'];
}
return $tickers;
Also your command $ticker['ticker'] doesn't make sense as it would store only 1 variable. I have changed it to $tickers[] = $results['ticker'] to store them in array. The result that way would look like:
array(3) {
[0]=>
string(1) "A"
[1]=>
string(2) "AA"
[2]=>
string(4) "WADV"
}

Your loop to extract the data isn't accessing the data at the right levels, you only need 1 loop which loops over the tickers array and then adds each ticker element to the new array (not sure what you were hoping the assignment was doing)...
foreach ($result['tickers'] as $res)
{
$ticker[] = $res['ticker'];
}

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

JSON only returning first character when decoding?

My JSON:
{"data":{"addresses":{"bitcoincash":"qzx3k8cq2e66k4glnt2derr5mppzc6xmvuxgsyp778","bitcoin":"1GjKuo1Q9sw8NytE31J5RPnVpYpEzp47hu","ethereum":"0xd7410e84e9c336937637e3cb472ad112c258ede3","litecoin":"LiQCBwuvW4RVuAg2dBNzS4fkviDwi8EBKa"},"code":"PGVD745Y","created_at":"2018-08-18T04:26:23Z","description":"dddd","expires_at":"2018-08-18T05:26:23Z","hosted_url":"https://commerce.coinbase.com/charges/example","id":"ddd","metadata":{"customer_id":"IuYBD5X7ylEV6g0xyTWi","name":"Guest#localhost.com"},"name":"ddd","payments":[],"pricing":{"local":{"amount":"19.85","currency":"USD"},"ethereum":{"amount":"0.063584000","currency":"ETH"},"bitcoin":{"amount":"0.00303719","currency":"BTC"},"bitcoincash":{"amount":"0.03345637","currency":"BCH"},"litecoin":{"amount":"0.32861518","currency":"LTC"}},"pricing_type":"fixed_price","resource":"charge","timeline":[{"status":"NEW","time":"2018-08-18T04:26:23Z"}]}}
My PHP:
$exec = json_encode($exec);
$json = json_decode($exec, TRUE);
echo $json['hosted_url'];
It just returns { always, in fact even if I put $json['safasfsaf'] it would still return {
What is the issue, the JSON is valid?
You can get hosted_url in this way (ERROR: you missing data $json['data']['hosted_url'])
also you can check your desired output here
<?php
$a = '{
"data": {
"addresses": {
"bitcoincash": "qzx3k8cq2e66k4glnt2derr5mppzc6xmvuxgsyp778",
"bitcoin": "1GjKuo1Q9sw8NytE31J5RPnVpYpEzp47hu",
"ethereum": "0xd7410e84e9c336937637e3cb472ad112c258ede3",
"litecoin": "LiQCBwuvW4RVuAg2dBNzS4fkviDwi8EBKa"
},
"code": "PGVD745Y",
"created_at": "2018-08-18T04:26:23Z",
"description": "dddd",
"expires_at": "2018-08-18T05:26:23Z",
"hosted_url": "https://commerce.coinbase.com/charges/example",
"id": "ddd",
"metadata": {
"customer_id": "IuYBD5X7ylEV6g0xyTWi",
"name": "Guest#localhost.com"
},
"name": "ddd",
"payments": [],
"pricing": {
"local": {
"amount": "19.85",
"currency": "USD"
},
"ethereum": {
"amount": "0.063584000",
"currency": "ETH"
},
"bitcoin": {
"amount": "0.00303719",
"currency": "BTC"
},
"bitcoincash": {
"amount": "0.03345637",
"currency": "BCH"
},
"litecoin": {
"amount": "0.32861518",
"currency": "LTC"
}
},
"pricing_type": "fixed_price",
"resource": "charge",
"timeline": [{
"status": "NEW",
"time": "2018-08-18T04:26:23Z"
}]
}
}';
$json = json_decode($a, TRUE);
echo "<pre>";
print_r($json['data']['hosted_url']);
You have error reporting turned off
This error is hidden for you
Warning: Illegal string offset 'hosted_url'
You can turn error reporting on with this code
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
For your code you need to replace $json['hosted_url'] with $json['data']['hosted_url']
$exec = getJson();
$json = json_decode($exec, TRUE);
echo $json['data']['hosted_url'];
Also response is already json so you must not json_encode it
I have noticed that, you are decode json data two time, so you are getting errors.
Hi, i have tried this way.
$exe = '{"data":{"addresses":{"bitcoincash":"qzx3k8cq2e66k4glnt2derr5mppzc6xmvuxgsyp778","bitcoin":"1GjKuo1Q9sw8NytE31J5RPnVpYpEzp47hu","ethereum":"0xd7410e84e9c336937637e3cb472ad112c258ede3","litecoin":"LiQCBwuvW4RVuAg2dBNzS4fkviDwi8EBKa"},"code":"PGVD745Y","created_at":"2018-08-18T04:26:23Z","description":"dddd","expires_at":"2018-08-18T05:26:23Z","hosted_url":"https://commerce.coinbase.com/charges/example","id":"ddd","metadata":{"customer_id":"IuYBD5X7ylEV6g0xyTWi","name":"Guest#localhost.com"},"name":"ddd","payments":[],"pricing":{"local":{"amount":"19.85","currency":"USD"},"ethereum":{"amount":"0.063584000","currency":"ETH"},"bitcoin":{"amount":"0.00303719","currency":"BTC"},"bitcoincash":{"amount":"0.03345637","currency":"BCH"},"litecoin":{"amount":"0.32861518","currency":"LTC"}},"pricing_type":"fixed_price","resource":"charge","timeline":[{"status":"NEW","time":"2018-08-18T04:26:23Z"}]}}';
$data = json_decode($exe, TRUE);
echo $data['data']['hosted_url'];

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'];

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.

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