JsonDecode on Null at an URL - php

I'm making a plugin that gets data from an external server through an encoded URL. To decode the output of the plugin I am using a JsonDecode, but it comes back 'NULL'everytime.
The code:
$json = file_get_contents($goodurl);
$data = json_decode($json);
var_dump($data);
This is the response when requesting the URL:
{
"schemaVersion": "1.0",
"catalogueVersion": "4.0.5651.20898",
"encoding": "UTF-8",
"action": "info",
"query": "catalogue",
"success": "true",
"response": {
"title": "Presentations 2Go",
"description": "Presentations2Go videoserver is an innovative solution to simply capture presentations and\/or lectures on video. The video image of the presenter is linked with the presentation and stored for later (re)use.",
"logoUrl": "https:\/\/DEMO-FORMS.presentations2go.eu\/P2G\/images\/logo\/logo.png",
"languages": [
{"lang": "en"},
{"lang": "nl"},
{"lang": "de"},
{"lang": "fr"},
{"lang": "kr"},
{"lang": "no"},
{"lang": "pt"},
{"lang": "dk"},
{"lang": "cn"},
{"lang": "ar"},
{"lang": "se"},
{"lang": "it"},
{"lang": "es"},
{"lang": "ru"},
{"lang": "cy"},
{"lang": "tw"}
],
"videoCount": "380",
"webmaster": "support#presentations2go.eu"
}
}
And this is the output in JSON:
object(stdClass)#83 (7) {
["schemaVersion"]=> string(3) "1.0"
["catalogueVersion"]=> string(14) "4.0.5651.20898"
["encoding"]=> string(5) "UTF-8"
["action"]=> string(4) "info"
["query"]=> string(9) "catalogue"
["success"]=> string(4) "true"
["response"]=> object(stdClass)#84 (6) {
["title"]=> string(17) "Presentations 2Go"
["description"]=> string(207) "Presentations2Go videoserver is an innovative solution to simply capture presentations and/or lectures on video. The video image of the presenter is linked with the presentation and stored for later (re)use."
["logoUrl"]=> string(63) "https://DEMO-FORMS.presentations2go.eu/P2G/images/logo/logo.png"
["languages"]=> array(16) {
[0]=> object(stdClass)#85 (1) {
["lang"]=> string(2) "en"
}
[1]=> object(stdClass)#86 (1) {
["lang"]=> string(2) "nl"
}
[2]=> object(stdClass)#87 (1) {
["lang"]=> string(2) "de"
}
[3]=> object(stdClass)#88 (1) {
["lang"]=> string(2) "fr"
}
[4]=> object(stdClass)#89 (1) {
["lang"]=> string(2) "kr"
}
[5]=> object(stdClass)#90 (1) {
["lang"]=> string(2) "no"
}
[6]=> object(stdClass)#91 (1) {
["lang"]=> string(2) "pt"
}
[7]=> object(stdClass)#92 (1) {
["lang"]=> string(2) "dk"
}
[8]=> object(stdClass)#93 (1) {
["lang"]=> string(2) "cn"
}
[9]=> object(stdClass)#94 (1) {
["lang"]=> string(2) "ar"
}
[10]=> object(stdClass)#95 (1) {
["lang"]=> string(2) "se"
}
[11]=> object(stdClass)#96 (1) {
["lang"]=> string(2) "it"
}
[12]=> object(stdClass)#97 (1) {
["lang"]=> string(2) "es"
}
[13]=> object(stdClass)#98 (1) {
["lang"]=> string(2) "ru"
}
[14]=> object(stdClass)#99 (1) {
["lang"]=> string(2) "cy"
}
[15]=> object(stdClass)#100 (1) {
["lang"]=> string(2) "tw"
}
}
["videoCount"]=> string(3) "378"
["webmaster"]=> string(27) "support#presentations2go.eu"
}
}
I'm not that experienced JSON so I suspect there might be a syntax error in there. But I'm not sure what and how to solve it.

You're getting an object instead of an array.
Simply write:
$data = json_decode($json, true);
To receive an associative array.
From the docs: http://php.net/manual/en/function.json-decode.php

Use this code
$data = json_decode($json,true);

You are getting an object instead of an array.
To receive an associative array.
$data = json_decode($json, true);
or you can access or get value of object like
echo $data->catalogueVersion;

Everyone already told you to set json_decode to true, when true returned objects will be converted into associative arrays., link
$data = json_decode($json, true);
I would suggest using the code below to view your array. Its is easier to read that way.
echo "<pre>";
print_r($array);
echo "</pre>";

Related

PHP Convert multidimensional array key to be array multidimensional value

I have problem formatting array to become fancytree format, below array output from db:
array(44) {
[0]=>
array(3) {
["id"]=>
string(2) "35"
["title"]=>
string(28) "ROOT1"
["path"]=>
string(28) "ROOT1"
}
[1]=>
array(3) {
["id"]=>
string(2) "36"
["title"]=>
string(27) "SUB_A"
["path"]=>
string(56) "ROOT1>SUB_A"
}
[2]=>
array(3) {
["id"]=>
string(2) "39"
["title"]=>
string(12) "SUB_A_1"
["path"]=>
string(69) "ROOT1>SUB_A>SUB_A_1"
}
[3]=>
array(3) {
["id"]=>
string(2) "37"
["title"]=>
string(28) "SUB_A_2"
["path"]=>
string(85) "ROOT1>SUB_A>SUB_A_2"
}
[4]=>
array(3) {
["id"]=>
string(2) "40"
["title"]=>
string(30) "SUB_A_3"
["path"]=>
string(87) "ROOT1>SUB_A>SUB_A_3"
}
[5]=>
array(3) {
["id"]=>
string(2) "43"
["title"]=>
string(19) "SUB_A_4"
["path"]=>
string(76) "ROOT1>SUB_A>SUB_A_4"
}
[6]=>
array(3) {
["id"]=>
string(2) "41"
["title"]=>
string(12) "SUB_A_5"
["path"]=>
string(69) "ROOT1>SUB_A>SUB_A_5"
}
[7]=>
array(3) {
["id"]=>
string(1) "1"
["title"]=>
string(20) "ROOT2"
["path"]=>
string(20) "ROOT2"
}
[8]=>
array(3) {
["id"]=>
string(2) "30"
["title"]=>
string(37) "ROOT3"
["path"]=>
string(37) "ROOT3"
}
[9]=>
array(3) {
["id"]=>
string(2) "34"
["title"]=>
string(21) "SUB_B"
["path"]=>
string(59) "ROOT3>SUB_B"
}
[10]=>
array(3) {
["id"]=>
string(2) "31"
["title"]=>
string(15) "SUB_C"
["path"]=>
string(53) "ROOT3>SUB_C"
}
I want to format values of path become structured array, here is what I try:
function format(array $data) : array
{
$single = [];
// format to single data
foreach ($data as $value) {
$single[] = $value['path'];
}
$result = [];
foreach ($single as $path) {
$parts = explode('>', $path);
$section = &$result;
$sectionName = '';
foreach ($parts as $part) {
$sectionName = $part;
if (array_key_exists($sectionName, $section) === FALSE) {
$section[$sectionName] = [];
}
$section = &$section[$sectionName];
}
}
return $result;
}
result:
array(3) {
["ROOT1"]=>
array(1) {
["SUB_A"]=>
array(5) {
["SUB_A_1"]=>
array(0) {
}
["SUB_A_2"]=>
array(0) {
}
["SUB_A_3"]=>
array(0) {
}
["SUB_A_4"]=>
array(0) {
}
["SUB_A_5"]=>
array(0) {
}
}
}
["ROOT2"]=>
array(0) {
}
["ROOT3"]=>
array(2) {
["SUB_B"]=>
array(0) {
}
["SUB_C"]=>
array(0) {
}
}
i need to include values of id and title to each path as expected result:
array(3) {
[0]=>
array(3) {
["title"]=>
string(5) "ROOT1"
["id"]=>
int(35)
["children"]=>
array(1) {
[0]=>
array(3) {
["title"]=>
string(5) "SUB_A"
["id"]=>
int(36)
["children"]=>
array(5) {
[0]=>
array(2) {
["title"]=>
string(7) "SUB_A_1"
["id"]=>
int(39)
}
[1]=>
array(2) {
["title"]=>
string(7) "SUB_A_2"
["id"]=>
int(37)
}
[2]=>
array(2) {
["title"]=>
string(7) "SUB_A_3"
["id"]=>
int(40)
}
[3]=>
array(2) {
["title"]=>
string(7) "SUB_A_4"
["id"]=>
int(43)
}
[4]=>
array(2) {
["title"]=>
string(7) "SUB_A_5"
["id"]=>
int(41)
}
}
}
}
}
[1]=>
array(2) {
["title"]=>
string(5) "ROOT2"
["id"]=>
int(1)
}
[2]=>
array(3) {
["title"]=>
string(5) "ROOT3"
["id"]=>
int(30)
["children"]=>
array(2) {
[0]=>
array(2) {
["title"]=>
string(5) "SUB_B"
["id"]=>
int(34)
}
[1]=>
array(2) {
["title"]=>
string(5) "SUB_C"
["id"]=>
int(31)
}
}
}
}
I would be grateful for any help you are able to provide.
Here's how I would do it. Test
I used arrow functions to reduce the amount of lines and there are inline comments to explain what I did.
<?php
$data = [["id"=> "35", "title"=> "ROOT1", "path"=> "ROOT1"], ["id"=> "36", "title"=> "SUB_A", "path"=> "ROOT1>SUB_A"], ["id"=> "37", "title"=> "SUB_A_1", "path"=> "ROOT1>SUB_A>SUB_A_1"], ["id"=> "38", "title"=> "SUB_A_2", "path"=> "ROOT1>SUB_A>SUB_A_2"], ["id"=> "39", "title"=> "SUB_A_3", "path"=> "ROOT1>SUB_A>SUB_A_3"], ["id"=> "40", "title"=> "SUB_A_4", "path"=> "ROOT1>SUB_A>SUB_A_4"], ["id"=> "41", "title"=> "SUB_A_5", "path"=> "ROOT1>SUB_A>SUB_A_5"], ["id"=> "1", "title"=> "ROOT2", "path"=> "ROOT2"], ["id"=> "30", "title"=> "ROOT3", "path"=> "ROOT3"], ["id"=> "34", "title"=> "SUB_B", "path"=> "ROOT3>SUB_B"], ["id"=> "31", "title"=> "SUB_C", "path"=> "ROOT3>SUB_C"]];
// The path is defaulted to an empty string, so the regex would return the highest level elements only because they don't have any `>`
function get_children($data, $path = '')
{
$results = array_values(array_filter($data, fn($item) => preg_match("/^{$path}[^>]+$/", $item['path'])));
// This regex, uses the passed path (e.g ROOT1) and searches for elements with anything but another `>`, because `>` signifies an inner directory.
// So this would return elements with a path like `ROOT1>SUB_A, ROOT1>SUB_B` but not `ROOT1>SUB_A>SUB_A_1`
foreach($results as $i => $result) {
// then I iterate through the result to get the element's children
$children = array_values(get_children($data, "{$result['path']}>"));
if (count($children)) $results[$i]['children'] = $children;
unset($results[$i]['path']); // Removing the path key from the array
}
return $results;
}
$format = fn($data) => get_children($data);
print_r($format($data));

Print data retrieved in JSON on a PHP

I'm trying to print a table with the list of Monitoring Groups from data retrieved from a REST API. The results come back in JSON. Below is the JSON data:
{
"code": 0,
"message": "success",
"data":
[
{
"group_id": "169839000000116001",
"display_name": "MTI Servers",
"description": "",
"monitors":
[
]
},
{
"group_id": "169839000000180001",
"display_name": "PRB Servers",
"description": "",
"monitors":
[
"169839000000179003",
"169839000000176013",
"169839000000175003",
"169839000000176007"
]
},
{
"group_id": "169839000000046270",
"display_name": "DB Servers",
"description": "",
"monitors":
[
"169839000000051011",
"169839000000047023",
"169839000000078001"
]
},
{
"group_id": "169839000000025200",
"display_name": "EXT Apps",
"description": "External Monitoring of Applications",
"monitors":
[
"169839000000025274",
"169839000000025377",
"169839000000025359",
"169839000000025369",
"169839000000025385",
"169839000000025226"
]
},
{
"group_id": "169839000000025109",
"display_name": "EXT Services",
"description": "External monitoring of services.",
"monitors":
[
"169839000000046165",
"169839000000025256",
"169839000000025168",
"169839000000025202",
"169839000000025189",
"169839000000025217",
"169839000000025265"
]
},
{
"group_id": "169839000000046015",
"display_name": "ZMB Servers",
"description": "",
"monitors":
[
"169839000000050017",
"169839000000050025",
"169839000000049001",
"169839000000050001",
"169839000000053019",
"169839000000051003",
"169839000000050009"
]
},
{
"group_id": "169839000000046282",
"display_name": "NWK Devices",
"description": "",
"monitors":
[
"169839000000082009",
"169839000000084077",
"169839000000084001",
"169839000000082229"
]
},
{
"group_id": "169839000000046013",
"display_name": "VBR Servers",
"description": "",
"monitors":
[
"169839000000047007"
]
},
{
"group_id": "169839000000054197",
"display_name": "LNX Servers",
"description": "",
"monitors":
[
"169839000000060483"
]
},
{
"group_id": "169839000000046020",
"display_name": "VSP Servers",
"description": "",
"monitors":
[
"169839000000060177",
"169839000000060170",
"169839000000060088",
"169839000000060095",
"169839000000060102",
"169839000000060109",
"169839000000054102"
]
},
{
"group_id": "169839000000046058",
"display_name": "WND Servers",
"description": "",
"monitors":
[
"169839000000066001",
"169839000000063119"
]
},
{
"group_id": "169839000000128001",
"display_name": "TPT Servers",
"description": "",
"monitors":
[
"169839000000143041",
"169839000000148017",
"169839000000127035",
"169839000000123003",
"169839000000126011",
"169839000000122011",
"169839000000129001",
"169839000000158028"
]
}
]
}
I want to print the Group ID, Name, Description and the list of monitor IDs that belong to the group. I'm using json_decode but I cant seem to read the correct variables from the array.
Here's the code I have so far:
`<?php
/**
* Connect to the Site API and extract the list of monitor groups
*/
// URL to fetch
$url = "https://www.mymonitorsite.com/api/monitor_groups";
// Initialize cURL session
$ch = curl_init($url);
// Option to Return the Result, rather than just true/false
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set Custom Headers
$headers = array(
'Authorization: Authtoken 12345678901234567890123456789012',
'Content-Type: application/json;charset=UTF-8',
'Accept: application/json; version=2.0',
);
// Option to set the custom headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Perform the request, and save content to $result
$mongrps_json = curl_exec($ch);
// Close the cURL resource, and free up system resources!
curl_close($ch);
// Decode json data into a PHP Array
$mongrps_array = json_decode($mongrps_json, true);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Monitor Group Test</title>
</head>
<body>
<?php
// List the first monitor group here (test)
echo "Group ID = " . $mongrps_array->data[0]->group_id . "<br>";
echo "Group Name = " . $mongrps_array->data[0]->display_name . <br>";
?>
</body>
</html>
`
Here's a var_dump of the json_decode:
array(3) { ["code"]=> int(0) ["message"]=> string(7) "success" ["data"]=> array(12) { [0]=> array(4) { ["group_id"]=> string(18) "169839000000116001" ["display_name"]=> string(11) "MTI Servers" ["description"]=> string(0) "" ["monitors"]=> array(0) { } } [1]=> array(4) { ["group_id"]=> string(18) "169839000000180001" ["display_name"]=> string(11) "PRB Servers" ["description"]=> string(0) "" ["monitors"]=> array(4) { [0]=> string(18) "169839000000179003" [1]=> string(18) "169839000000176013" [2]=> string(18) "169839000000175003" [3]=> string(18) "169839000000176007" } } [2]=> array(4) { ["group_id"]=> string(18) "169839000000046270" ["display_name"]=> string(10) "DB Servers" ["description"]=> string(0) "" ["monitors"]=> array(3) { [0]=> string(18) "169839000000051011" [1]=> string(18) "169839000000047023" [2]=> string(18) "169839000000078001" } } [3]=> array(4) { ["group_id"]=> string(18) "169839000000025200" ["display_name"]=> string(8) "EXT Apps" ["description"]=> string(35) "External Monitoring of Applications" ["monitors"]=> array(6) { [0]=> string(18) "169839000000025274" [1]=> string(18) "169839000000025377" [2]=> string(18) "169839000000025359" [3]=> string(18) "169839000000025369" [4]=> string(18) "169839000000025385" [5]=> string(18) "169839000000025226" } } [4]=> array(4) { ["group_id"]=> string(18) "169839000000025109" ["display_name"]=> string(12) "EXT Services" ["description"]=> string(31) "External monitoring of services" ["monitors"]=> array(7) { [0]=> string(18) "169839000000046165" [1]=> string(18) "169839000000025256" [2]=> string(18) "169839000000025168" [3]=> string(18) "169839000000025202" [4]=> string(18) "169839000000025189" [5]=> string(18) "169839000000025217" [6]=> string(18) "169839000000025265" } } [5]=> array(4) { ["group_id"]=> string(18) "169839000000046015" ["display_name"]=> string(11) "ZMB Servers" ["description"]=> string(0) "" ["monitors"]=> array(7) { [0]=> string(18) "169839000000050017" [1]=> string(18) "169839000000050025" [2]=> string(18) "169839000000049001" [3]=> string(18) "169839000000050001" [4]=> string(18) "169839000000053019" [5]=> string(18) "169839000000051003" [6]=> string(18) "169839000000050009" } } [6]=> array(4) { ["group_id"]=> string(18) "169839000000046282" ["display_name"]=> string(11) "NWK Devices" ["description"]=> string(0) "" ["monitors"]=> array(4) { [0]=> string(18) "169839000000082009" [1]=> string(18) "169839000000084077" [2]=> string(18) "169839000000084001" [3]=> string(18) "169839000000082229" } } [7]=> array(4) { ["group_id"]=> string(18) "169839000000046013" ["display_name"]=> string(11) "VBR Servers" ["description"]=> string(0) "" ["monitors"]=> array(1) { [0]=> string(18) "169839000000047007" } } [8]=> array(4) { ["group_id"]=> string(18) "169839000000054197" ["display_name"]=> string(11) "LNX Servers" ["description"]=> string(0) "" ["monitors"]=> array(1) { [0]=> string(18) "169839000000060483" } } [9]=> array(4) { ["group_id"]=> string(18) "169839000000046020" ["display_name"]=> string(11) "VSP Servers" ["description"]=> string(0) "" ["monitors"]=> array(7) { [0]=> string(18) "169839000000060177" [1]=> string(18) "169839000000060170" [2]=> string(18) "169839000000060088" [3]=> string(18) "169839000000060095" [4]=> string(18) "169839000000060102" [5]=> string(18) "169839000000060109" [6]=> string(18) "169839000000054102" } } [10]=> array(4) { ["group_id"]=> string(18) "169839000000046058" ["display_name"]=> string(11) "WND Servers" ["description"]=> string(0) "" ["monitors"]=> array(2) { [0]=> string(18) "169839000000066001" [1]=> string(18) "169839000000063119" } } [11]=> array(4) { ["group_id"]=> string(18) "169839000000128001" ["display_name"]=> string(11) "TPT Servers" ["description"]=> string(0) "" ["monitors"]=> array(8) { [0]=> string(18) "169839000000143041" [1]=> string(18) "169839000000148017" [2]=> string(18) "169839000000127035" [3]=> string(18) "169839000000123003" [4]=> string(18) "169839000000126011" [5]=> string(18) "169839000000122011" [6]=> string(18) "169839000000129001" [7]=> string(18) "169839000000158028" } } } }
Use foreach loop to display the following data:
group_id
display_name
description and
monitors(as a comma separated list)
$mongrps_array = json_decode($mongrps_json, true);
foreach($mongrps_array['data'] as $arr){
foreach($arr as $key => $value){
if($key == "monitors"){
echo $key . ": " . implode(", ", $value) . "<br />";
}else{
echo $key . ": " . $value . "<br />";
}
}
echo "<br />";
}
I Just tried, should not be any issue to get the data you are looking for.
For example, to get the group_id of the first item in the array:
echo $decodedJson->data[0]->group_id;
Maybe you are trying to get the data as arrays? In this case, pass the parameter true to the json_decode function:
$decodedJson = json_decode($originalJson, true);
echo $decodedJson['data'][0]['group_id'];

Echo array with json_decode gives too many echoes

I do get the strings I intend to. But I also get the first letter (or number) of the other data in the json file.
E.g. I would like to have or should get the result:
/Barrafina
Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here.
Matt Ta-Min/
But instead I get
/Barrafina
ee
Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here.
5 5 E Eu uh h
Matt Ta-Min
/
What did I do wrong? here is the code:
(If you have time and energy to look the JSON you will see from where eg. 5 5 E Eu uh h comes.)
I appreciate any help.
<?php
$client_id = 'CLIENT_ID';
$client_secret = 'SECRET';
$request_date = date('Ymd');
$base_url = 'https://api.foursquare.com/v2/';
$endpoint = 'venues/explore?';
$params = 'near=London&limit=3&section=food&radius=1000';
$auth = "&client_id=$client_id&client_secret=$client_secret&v=$request_date";
$url = $base_url.$endpoint.$params.$auth;
$results = file_get_contents($url);
$json_results = json_decode($results,true);
//var_dump($json_results);
$items0 = $json_results['response']['groups']['0']['items']['0'];
$items1 = $json_results['response']['groups']['0']['items']['0']['tips'];
$items2 = $json_results['response']['groups']['0']['items']['0']['tips']['0'];
//<div style="align:center;">
foreach ( $items0+$items1 as $item){
echo '<li>';
echo $item['name'];
echo $item['text'];
}
foreach ( $items2 as $item){
print $item['firstName']; print '&nbsp'; print $item['lastName'];
}
HERE is the json decoded:
array(2) { ["meta"]=> array(2) { ["code"]=> int(200) ["requestId"]=> string(24) "55fb1f91498e70ad2e246eed" } ["response"]=> array(10) { ["suggestedFilters"]=> array(2) { ["header"]=> string(12) "Tap to show:" ["filters"]=> array(2) { [0]=> array(2) { ["name"]=> string(13) "With specials" ["key"]=> string(8) "specials" } [1]=> array(2) { ["name"]=> string(8) "Open now" ["key"]=> string(7) "openNow" } } } ["geocode"]=> array(8) { ["what"]=> string(0) "" ["where"]=> string(6) "london" ["center"]=> array(2) { ["lat"]=> float(51.50853) ["lng"]=> float(-0.12574) } ["displayString"]=> string(38) "London, Greater London, United Kingdom" ["cc"]=> string(2) "GB" ["geometry"]=> array(1) { ["bounds"]=> array(2) { ["ne"]=> array(2) { ["lat"]=> float(51.691643999656) ["lng"]=> float(0.33418999705203) } ["sw"]=> array(2) { ["lat"]=> float(51.284674044171) ["lng"]=> float(-0.50855792793694) } } } ["slug"]=> string(6) "london" ["longId"]=> string(17) "72057594040571679" } ["warning"]=> array(1) { ["text"]=> string(114) "There aren't a lot of results near you. Try something more general, reset your filters, or expand the search area." } ["headerLocation"]=> string(6) "London" ["headerFullLocation"]=> string(6) "London" ["headerLocationGranularity"]=> string(4) "city" ["query"]=> string(4) "food" ["totalResults"]=> int(246) ["suggestedBounds"]=> array(2) { ["ne"]=> array(2) { ["lat"]=> float(51.510800358799) ["lng"]=> float(-0.12174369837641) } ["sw"]=> array(2) { ["lat"]=> float(51.508100699014) ["lng"]=> float(-0.13015278468604) } } ["groups"]=> array(1) { [0]=> array(3) { ["type"]=> string(18) "Recommended Places" ["name"]=> string(11) "recommended" ["items"]=> array(1) { [0]=> array(4) { ["reasons"]=> array(2) { ["count"]=> int(0) ["items"]=> array(1) { [0]=> array(3) { ["summary"]=> string(20) "This spot is popular" ["type"]=> string(7) "general" ["reasonName"]=> string(23) "globalInteractionReason" } } } ["venue"]=> array(17) { ["id"]=> string(24) "53bab96d498e7e355fb53d6c" ["name"]=> string(9) "Barrafina" ["contact"]=> array(6) { ["phone"]=> string(13) "+442074401456" ["formattedPhone"]=> string(16) "+44 20 7440 1456" ["twitter"]=> string(13) "barrafinaadst" ["facebook"]=> string(15) "705351912878392" ["facebookUsername"]=> string(23) "BarrafinaAdelaideStreet" ["facebookName"]=> string(25) "Barrafina Adelaide Street" } ["location"]=> array(10) { ["address"]=> string(14) "10 Adelaide St" ["crossStreet"]=> string(13) "William IV St" ["lat"]=> float(51.509450528906) ["lng"]=> float(-0.12594824153122) ["postalCode"]=> string(8) "WC2N 4HZ" ["cc"]=> string(2) "GB" ["city"]=> string(6) "London" ["state"]=> string(14) "Greater London" ["country"]=> string(14) "United Kingdom" ["formattedAddress"]=> array(5) { [0]=> string(30) "10 Adelaide St (William IV St)" [1]=> string(6) "London" [2]=> string(14) "Greater London" [3]=> string(8) "WC2N 4HZ" [4]=> string(14) "United Kingdom" } } ["categories"]=> array(1) { [0]=> array(6) { ["id"]=> string(24) "4bf58dd8d48988d150941735" ["name"]=> string(18) "Spanish Restaurant" ["pluralName"]=> string(19) "Spanish Restaurants" ["shortName"]=> string(7) "Spanish" ["icon"]=> array(2) { ["prefix"]=> string(52) "https://ss3.4sqi.net/img/categories_v2/food/spanish_" ["suffix"]=> string(4) ".png" } ["primary"]=> bool(true) } } ["verified"]=> bool(false) ["stats"]=> array(3) { ["checkinsCount"]=> int(357) ["usersCount"]=> int(278) ["tipCount"]=> int(26) } ["url"]=> string(22) "http://barrafina.co.uk" ["price"]=> array(3) { ["tier"]=> int(2) ["message"]=> string(8) "Moderate" ["currency"]=> string(2) "£" } ["rating"]=> float(9) ["ratingColor"]=> string(6) "00B551" ["ratingSignals"]=> int(80) ["allowMenuUrlEdit"]=> bool(true) ["hours"]=> array(2) { ["status"]=> string(19) "Open until 11:00 PM" ["isOpen"]=> bool(true) } ["specials"]=> array(2) { ["count"]=> int(0) ["items"]=> array(0) { } } ["photos"]=> array(2) { ["count"]=> int(31) ["groups"]=> array(0) { } } ["hereNow"]=> array(3) { ["count"]=> int(0) ["summary"]=> string(11) "Nobody here" ["groups"]=> array(0) { } } } ["tips"]=> array(1) { [0]=> array(9) { ["id"]=> string(24) "55db9142498ede18f5b31b81" ["createdAt"]=> int(1440452930) ["text"]=> string(164) "Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here." ["type"]=> string(4) "user" ["canonicalUrl"]=> string(52) "https://foursquare.com/item/55db9142498ede18f5b31b81" ["likes"]=> array(3) { ["count"]=> int(2) ["groups"]=> array(0) { } ["summary"]=> string(7) "2 likes" } ["logView"]=> bool(true) ["todo"]=> array(1) { ["count"]=> int(0) } ["user"]=> array(5) { ["id"]=> string(8) "98683884" ["firstName"]=> string(4) "Matt" ["lastName"]=> string(6) "Ta-Min" ["gender"]=> string(4) "male" ["photo"]=> array(2) { ["prefix"]=> string(31) "https://irs1.4sqi.net/img/user/" ["suffix"]=> string(30) "/98683884-1MJ0OTISTPZWSBRJ.jpg" } } } } ["referralId"]=> string(30) "e-3-53bab96d498e7e355fb53d6c-0" } } } } } }
Here is JSON
{"meta":{"code":200,"requestId":"55fbde58498e7fdbd12f8fb2"},"response":{"suggestedFilters":{"header":"Tap to show:","filters":[{"name":"With specials","key":"specials"},{"name":"Open now","key":"openNow"}]},"geocode":{"what":"","where":"london","center":{"lat":51.50853,"lng":-0.12574},"displayString":"London, Greater London, United Kingdom","cc":"GB","geometry":{"bounds":{"ne":{"lat":51.691643999655895,"lng":0.33418999705203406},"sw":{"lat":51.28467404417054,"lng":-0.5085579279369435}}},"slug":"london","longId":"72057594040571679"},"warning":{"text":"There aren't a lot of results near you. Try something more general, reset your filters, or expand the search area."},"headerLocation":"London","headerFullLocation":"London","headerLocationGranularity":"city","query":"food","totalResults":246,"suggestedBounds":{"ne":{"lat":51.5108003587992,"lng":-0.12174369837640672},"sw":{"lat":51.50810069901375,"lng":-0.1301527846860385}},"groups":[{"type":"Recommended Places","name":"recommended","items":[{"reasons":{"count":0,"items":[{"summary":"This spot is popular","type":"general","reasonName":"globalInteractionReason"}]},"venue":{"id":"53bab96d498e7e355fb53d6c","name":"Barrafina","contact":{"phone":"+442074401456","formattedPhone":"+44 20 7440 1456","twitter":"barrafinaadst","facebook":"705351912878392","facebookUsername":"BarrafinaAdelaideStreet","facebookName":"Barrafina Adelaide Street"},"location":{"address":"10 Adelaide St","crossStreet":"William IV St","lat":51.50945052890648,"lng":-0.1259482415312226,"postalCode":"WC2N 4HZ","cc":"GB","city":"London","state":"Greater London","country":"United Kingdom","formattedAddress":["10 Adelaide St (William IV St)","London","Greater London","WC2N 4HZ","United Kingdom"]},"categories":[{"id":"4bf58dd8d48988d150941735","name":"Spanish Restaurant","pluralName":"Spanish Restaurants","shortName":"Spanish","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/spanish_","suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":357,"usersCount":278,"tipCount":26},"url":"http:\/\/barrafina.co.uk","rating":9.0,"ratingColor":"00B551","ratingSignals":80,"allowMenuUrlEdit":true,"hours":{"status":"Closed until Noon","isOpen":false},"specials":{"count":0,"items":[]},"photos":{"count":31,"groups":[]},"hereNow":{"count":0,"summary":"Nobody here","groups":[]}},"tips":[{"id":"55db9142498ede18f5b31b81","createdAt":1440452930,"text":"Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here.","type":"user","canonicalUrl":"https:\/\/foursquare.com\/item\/55db9142498ede18f5b31b81","likes":{"count":2,"groups":[],"summary":"2 likes"},"logView":true,"todo":{"count":0},"user":{"id":"98683884","firstName":"Matt","lastName":"Ta-Min","gender":"male","photo":{"prefix":"https:\/\/irs1.4sqi.net\/img\/user\/","suffix":"\/98683884-1MJ0OTISTPZWSBRJ.jpg"}}}],"referralId":"e-3-53bab96d498e7e355fb53d6c-0"}]}]}}

Accesing JSON response data via PHP

I'm using the Paypal API PHP REST SDK. I got a response that looks like in JSON format but i'm unable to access the properties inside the object and array.
How do I access the "state" properties from this JSON response via PHP? The response is being wrapped by the object of Paypal\Api\Payment type. foreach looping returns NULL
var_dump($response) looks like below:
object(PayPal\Api\Payment)#8 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(8) {
["id"]=>
string(28) "PAY-8JC052XXXXKKZMQNQ"
["create_time"]=>
string(20) "2013-12-19T10:19:34Z"
["update_time"]=>
string(20) "2013-12-19T10:20:38Z"
["state"]=>
string(8) "approved"
["intent"]=>
string(4) "sale"
["payer"]=>
object(PayPal\Api\Payer)#33 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(2) {
["payment_method"]=>
string(6) "paypal"
["payer_info"]=>
object(PayPal\Api\PayerInfo)#30 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(5) {
["email"]=>
string(11) "some#email.com"
["first_name"]=>
string(6) "fname"
["last_name"]=>
string(5) "lname"
["payer_id"]=>
string(13) "UAGGF3392CUTG"
["shipping_address"]=>
object(PayPal\Api\Address)#31 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(5) {
["line1"]=>
string(26) "Address"
["city"]=>
string(13) "City"
["state"]=>
string(8) "State"
["postal_code"]=>
string(5) "000000"
["country_code"]=>
string(2) "US"
}
}
}
}
}
}
["transactions"]=>
array(1) {
[0]=>
object(PayPal\Api\Transaction)#34 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(4) {
["amount"]=>
object(PayPal\Api\Amount)#35 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(3) {
["total"]=>
string(4) "1.00"
["currency"]=>
string(3) "USD"
["details"]=>
object(PayPal\Api\Details)#36 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(1) {
["subtotal"]=>
string(4) "1.00"
}
}
}
}
["description"]=>
string(33) "Item name: 1"
["item_list"]=>
object(PayPal\Api\ItemList)#37 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(1) {
["items"]=>
array(1) {
[0]=>
object(PayPal\Api\Item)#38 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(4) {
["name"]=>
string(20) "Item name"
["price"]=>
string(4) "1.00"
["currency"]=>
string(3) "USD"
["quantity"]=>
string(1) "1"
}
}
}
}
}
["related_resources"]=>
array(1) {
[0]=>
object(PayPal\Api\RelatedResources)#40 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(1) {
["sale"]=>
object(PayPal\Api\Sale)#42 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(7) {
["id"]=>
string(17) "5DH04XXX63X"
["create_time"]=>
string(20) "2013-12-19T10:19:34Z"
["update_time"]=>
string(20) "2013-12-19T10:20:38Z"
["state"]=>
string(9) "completed"
["amount"]=>
object(PayPal\Api\Amount)#44 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(2) {
["total"]=>
string(4) "1.00"
["currency"]=>
string(3) "USD"
}
}
["parent_payment"]=>
string(28) "PAY-8JC05XXXXKZMQNQ"
["links"]=>
array(3) {
[0]=>
object(PayPal\Api\Links)#46 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(3) {
["href"]=>
string(65) "https://api.sandbox.paypal.com/v1/payments/sale/5DHXX91763X"
["rel"]=>
string(4) "self"
["method"]=>
string(3) "GET"
}
}
[1]=>
object(PayPal\Api\Links)#47 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(3) {
["href"]=>
string(72) "https://api.sandbox.paypal.com/v1/payments/sale/5DHXXA691763X/refund"
["rel"]=>
string(6) "refund"
["method"]=>
string(4) "POST"
}
}
[2]=>
object(PayPal\Api\Links)#48 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(3) {
["href"]=>
string(79) "https://api.sandbox.paypal.com/v1/payments/payment/PAY-8JC052914XX1034SKKZMQNQ"
["rel"]=>
string(14) "parent_payment"
["method"]=>
string(3) "GET"
}
}
}
}
}
}
}
}
}
}
}
["links"]=>
array(1) {
[0]=>
object(PayPal\Api\Links)#49 (1) {
["_propMap":"PayPal\Common\PPModel":private]=>
array(3) {
["href"]=>
string(79) "https://api.sandbox.paypal.com/v1/payments/payment/PAY-8JC0XX914D601034SKKZMQNQ"
["rel"]=>
string(4) "self"
["method"]=>
string(3) "GET"
}
}
}
}
}
I tried json_decode($response) but it returned NULL so i assumed that this is already the correct JSON format.
I tried echo $response->id and it returns blank
I've also tried multiple variations of foreach ($response->id as $value) { var_dump($value); } which also returns nothing
Help!
If you use only json_decode($result) it will not convert entire objects into an array.
So simply use
$result=json_decode($result, true, 512);
It will convert all the objects into associative array recursively.
Try it. It works for me.
It turns out that this is not a standard JSON format. For some reason the Paypal API SDK return it in their own "json" format through this line
$ret->fromJson($json);
return $ret;
I just skipped that and return $json instead and it gives me the format that i can put into json_decode for further processing.
return $json;
That took me 1 full freaking day! Pff...
You can also use
$response->toJSON();
then you can use
$result = json_decode($response);
echo ($result->state);
Convert json to a string then store the content in an array (decode it with json_decode).

Parsing particular value in JSON via PHP from Mapquest API

I am having trouble targeting the particular value in the array. I am trying to target the 'lng' and 'lat'. I feel like I'm close, and have tried several different ways to target. Currently trying this:
$json = file_get_contents($jsonurl);
$output = json_decode($json, true);
$latitude=$output['results']['locations']['latLng'][0];
$longitude=$output['results']['locations']['latLng'][1];
The JSON is:
array(3) {
["results"]=>
array(1) {
[0]=>
array(2) {
["locations"]=>
array(1) {
[0]=>
array(19) {
["latLng"]=>
array(2) {
["lng"]=>
float(-122.5008)
["lat"]=>
float(47.2629)
}
["adminArea4"]=>
string(13) "Pierce County"
["adminArea5Type"]=>
string(4) "City"
["adminArea4Type"]=>
string(6) "County"
["adminArea5"]=>
string(6) "Tacoma"
["street"]=>
string(0) ""
["adminArea1"]=>
string(2) "US"
["adminArea3"]=>
string(2) "WA"
["type"]=>
string(1) "s"
["displayLatLng"]=>
array(2) {
["lng"]=>
float(-122.5008)
["lat"]=>
float(47.2629)
}
["linkId"]=>
int(0)
["postalCode"]=>
string(5) "98406"
["sideOfStreet"]=>
string(1) "N"
["dragPoint"]=>
bool(false)
["adminArea1Type"]=>
string(7) "Country"
["geocodeQuality"]=>
string(3) "ZIP"
["geocodeQualityCode"]=>
string(5) "Z1XAA"
["mapUrl"]=>
string(186) "http://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luub2gu2ll,7w=o5-9uaauz&type=map&size=225,160&pois=purple-1,47.2629,-122.5008,0,0|&center=47.2629,-122.5008&zoom=12&rand=-8386350"
["adminArea3Type"]=>
string(5) "State"
}
}
["providedLocation"]=>
array(1) {
["location"]=>
string(5) "98406"
}
}
}
["options"]=>
array(3) {
["ignoreLatLngInput"]=>
bool(false)
["maxResults"]=>
int(-1)
["thumbMaps"]=>
bool(true)
}
["info"]=>
array(3) {
["copyright"]=>
array(3) {
["text"]=>
string(22) "© 2013 MapQuest, Inc."
["imageUrl"]=>
string(35) "http://api.mqcdn.com/res/mqlogo.gif"
["imageAltText"]=>
string(22) "© 2013 MapQuest, Inc."
}
["statuscode"]=>
int(0)
["messages"]=>
array(0) {
}
}
}
Try
$latitude=$output['results'][0]['locations'][0]['latLng']['lat'];
$longitude=$output['results'][0]['locations'][0]['latLng']['lng'];

Categories