This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
Why does this PHP code just echo "Array"?
(6 answers)
Closed 2 years ago.
I have really been struggling with outputting the content of a json data I received from a rest API response correctly. I have searched a lot and tried different ways but I noticed everyone's is always unique...below is my code..specifically of consideration is the "headers_field" it is an array with a lot of values and keys...and I want to also output these values with the keys...While the ("data") has two values with it...below is what I have tried also but I am just getting the first result from the loop while it returns ("headers_field": Array), ("box: Array")..I used Curl. Kindly look below. Thanks.
{
"data": [
{
"approved": null,
"approved_user_id": null,
"boxes": [],
"created": "2020-05-19T21",
"created_at": "2020-05-19T21",
"edited": null,
"edited_in_affiliate": null,
"edited_in_hdr": null,
"edited_in_web_app": null,
"erp_project_id": null,
"error_description": "",
"header_fields": [
{
"boxes": [],
"code": "creditor_number",
"data_type": "",
"error": "",
"feature_id": nvnnn,
"value": "hhhhh"
},
{
"boxes": [],
"code": "payment_account_number",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "order_number",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "total_amount_incl_vat",
"data_type": "",
"error": "",
"feature_id": mmm
"value": "hhh"
},
{
"approved": null,
"approved_user_id": null,
"boxes": [],
"created": "2020-05-19",
"created_at": "2020-05-19",
"edited": null,
"edited_in_affiliate": null,
"edited_in_hdr": null,
"edited_in_web_app": null,
"erp_project_id": null,
"error_description": "",
"header_fields": [
{
"boxes": [],
"code": "reference",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "payment_swift_bic",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "recipient_vat_reg_no",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "joint_payment_id",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "catalog_debitor_id",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "case_number",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "payment_account_number",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "payment_iban",
"data_type": "",
"error": "",
"value": ""
}
],
"id": 00000,
"image": "https://skkkkkllllllllll
"line_items": [],
"note": "",
"organization_id": 11111,
"organization_voucher_id": 7777,
"page_count": 1,
"status": "successful",
"type": "voucher",
"upload_type": "affiliate",
"uploaded_by_user_id": 0000001
"user_payment_method": "",
"user_voucher_type": ""
}
],
"meta": {
"count": 2
}
}
MY LOOP OPERATION
.....
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$results= curl_exec($ch);
$g= json_decode($results, true);
$i=0;
$g_length =count($g["data"]);//to count through the child array
for ($i=0; $i < ($g_length);$i++)
{
$k= $g["data"][$i]; //asssigning the array position to a variable
foreach($k as $mydata=>$mvalue) {
$hey = trim($mvalue); //Removes white spaces
if ($mvalue !=="")
echo $mydata. " : " . $mvalue . "<br>";
else
echo "This is empty. <br/>";
///////////////////////////////////////////
foreach($mvalue as $lkey=>$lvalue)
{
$u=is_array($mvalue);
if(($u) and !empty($u))
echo $lkey. ":" . $lvalue. "<br>";
else
echo "what? <br/>";
///////////
foreach($lvalue as $okey=>$ovalue)
{
echo $okey. ":". $value. "</n>";
/////
foreach($ovalue as $key=>$value)
{
$v=is_array($value);
if(($v) and !empty($v))
echo $key. ":" . $value. "<br>";
else
echo "hello";
//print_r($key);
/////
}
}
//////////
}
//////////////////////////////////////////
}
Provided you know how deep the array is that you get back from the API or how many dimensions and you know the key structure will be the same you could use something like this:
NOTE: I took your JSON and did a quick and dirty to spit out all the keys and values - including the nested header fields. Essentially its based on whether the value is an ARRAY. If you know the structure you are expecting you could make this more elegant by creating an array map and a function to process all vals that are sub arrays.
Anyway - I hope the below helps you as a starter:
foreach($theDecodedData['data']["header_fields"] as $row){
foreach($row as $key => $val){
if(!is_array($val)){
echo "$key: $val \n";
}
else{
echo "Contents of $key \n";
foreach($val as $vkey => $vval){
if(!is_array($vval)){
echo "$vkey: $vval \n";
}
else{
echo "Contents of $vkey \n";
foreach($vval as $vvvkey => $vvvval){
if(!is_array($vvvval)){
echo "$vvvkey: $vvvval \n";
}
else{
echo "Contents of $vvvkey \n";
foreach($vvvval as $vvvvkey => $vvvvval){
echo "$vvvvkey: $vvvvval \n";
}
}
}
}
}
}
}
}
Related
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
I'm trying to parse data returned by the Jotform API.
I'm successfully echoing the data but I'm also getting unnecessary additional lines of text.
My PHP code is:
include "JotForm.php";
$jotformAPI = new JotForm("myapikey");
$submissions = $jotformAPI->getFormSubmissions("myformid");
var_dump($submissions );
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
foreach ($detail as $d) {
echo $d[1]['answer']['first'] . '<br>';
}
}
result of var_dump($submissions );
{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}],
}
And here is the result I'm getting:
1
0
0
0
C
0
LeBron
I had to repair your invalid json string...
Code: (Demo)
$json = '{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}}]
}';
foreach (json_decode($json, true)['content'] as $set) {
echo "{$set['answers'][1]['answer']['first']} {$set['answers'][1]['answer']['last']}\n";
}
Output:
LeBron James
I'm a little fuzzy on the action of the jot functions, but maybe it's supposed to be like this:
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
echo $detail['answers'][1]['answer']['first'] . '<br>';
}
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'];
I have a json response like this:
{
"status": 200,
"msg": "OK",
"result": {
"folders": [
{
"id": "3812454",
"name": ".subtitles"
},
{
"id": "3812455",
"name": ".videothumb"
}
],
"files": [
{
"name": "Angamaly Diaries HD.MP4.mp4",
"cblock": null,
"sha1": "fcc2c99f2db6e3e8a700c3247206a1c2148e14cb",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "713544705",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "PjUv5IYA2J8"
},
{
"name": "Take Off 2017.MP4.mp4",
"cblock": null,
"sha1": "2fe7fb4d45322a085d41239d6429d1cc8e94e2ce",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "954148848",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "BIBcjWqF0_I"
},
{
"name": "Rangoon 2017 Tamil.MP4.mp4",
"cblock": null,
"sha1": "c685e7c11636982860ae7f34b671a20fc746feee",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "779899588",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "00D7GzP6mls"
},
{
"name": "The Zookeeper’s Wife 2017.MP4.mp4.mp4",
"cblock": null,
"sha1": "a143faafbd8a6eaf2276f25cd642ac3019d71ffc",
"folderid": "3812453",
"upload_at": "1510256266",
"status": "active",
"size": "550126461",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "bwUhqbiJJWQ"
}
]
}
}
And I have a string with this text:
"Watch Take Off 2017 Malayalam Full Movie Online Free"
Now I need to get the linkextid of
"name": "Take Off 2017.MP4.mp4"
from JSON response. There is one more thing that I have so much similar data on the JSON response, but I need to the get name that matches maximum words from string using PHP.
<?php
$json_data='{"status":200,"msg":"OK","result":{"folders":[{"id":"3812454","name":".subtitles"},{"id":"3812455","name":".videothumb"}],"files":[{"name":"Angamaly Diaries HD.MP4.mp4","cblock":null,"sha1":"fcc2c99f2db6e3e8a700c3247206a1c2148e14cb","folderid":"3812453","upload_at":"1510255141","status":"active","size":"713544705","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"PjUv5IYA2J8"},{"name":"Take Off 2017.MP4.mp4","cblock":null,"sha1":"2fe7fb4d45322a085d41239d6429d1cc8e94e2ce","folderid":"3812453","upload_at":"1510255141","status":"active","size":"954148848","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"BIBcjWqF0_I"},{"name":"Rangoon 2017 Tamil.MP4.mp4","cblock":null,"sha1":"c685e7c11636982860ae7f34b671a20fc746feee","folderid":"3812453","upload_at":"1510255141","status":"active","size":"779899588","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"00D7GzP6mls"},{"name":"The Zookeeper’s Wife 2017.MP4.mp4.mp4","cblock":null,"sha1":"a143faafbd8a6eaf2276f25cd642ac3019d71ffc","folderid":"3812453","upload_at":"1510256266","status":"active","size":"550126461","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"bwUhqbiJJWQ"}]}}';
$data=json_decode($json_data,true);
$files=$data['result']['files'];
$search="Watch Take Off 2017 Malayalam Full Movie Online Free";
$search_array=explode(' ',$search);
foreach($search_array as $key=>$row){
$search_array[$key]=trim($row);
}
$match=[];
foreach($files as $key=>$row){
$match_count=0;
foreach($search_array as $s){
if(preg_match('/'.$s.'/',$row['name'])){
$match_count+=1;
}
}
$match[$key]=$match_count;
}
rsort($match);
print_r($files[$match[0]]['linkextid'])
?>
Not the best solution in the world but this should work:
<?php
function compare_strings($s1, $s2) {
$s1Words = explode(' ', $s1);
$s2Words = explode(' ', $s2);
$wordCount = 0;
foreach ($s1Words as $word) {
if ( strpos($s2Words, $word) ) {
$wordCount++;
}
}
return $wordCount;
}
function get_movie_linkextid($data, $name) {
$bestMatchIndex = 1;
$bestMatchScore = 0;
foreach ($data['result']['files'] as $i => $movie) {
$currentScore = compare_strings($movie['name'], $name);
if ($currentScore > $bestMatchScore) {
$bestMatchScore = $currentScore;
$bestMatchIndex = $i;
}
}
return $data['result']['files'][$bestMatchIndex]['linkextid'];
}
$data = json_decode($yourJsonData, true);
$name = "Watch Take Off 2017 Malayalam Full Movie Online Free";
echo get_movie_linkextid($data, $name);
?>
The code just parses your JSON into a variable and than goes through all the 'files' comparing their names with the string you provided the determine the best match. After that it just return the linkextid.
I Didn't tested this code but the important is to get the idea since you will have to adapt it to be more generic anyway.
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;