I would like to get the value of "Records"
When is try this code:
$json = file_get_contents('URL');
var_dump($json);
This is the result:
string(25289) "{ "ProductsSummary": { "Records": 10, "TotalRecords": 2874, "TotalPages": 288, "CurrentPage": 1 }, "Products": [ { "...
When I try this code
$json = file_get_contents('URL');
$obj = json_decode($json);
echo $obj;
echo $obj->{'ProductsSummary'}->{'Records'};
echo $obj->ProductsSummary->Records;
echo $obj[0]->ProductsSummary->Records;
echo $obj->ProductsSummary[0]->Records;
echo $obj->ProductsSummary[1];
The Output is:
{ "ProductsSummary": { "Records": 10, "TotalRecords": 2879, "TotalPages": 288, "CurrentPage": 1 }, "Products": [ { "Last.... }
Notice: Trying to get property of non-object in ...
Notice: Trying to get property of non-object in ...
Notice: Trying to get property of non-object in ...
Since you do not have valid JSON, I'm pretty sure that json_decode() is just failing. As per the manual:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
You can verify that with e.g. the is_null() function:
$obj = json_decode($json);
if( is_null($obj) ){
// Invalid JSON, don't need to keep on working on it
}else{
// Read data
}
... although the proper way would be to explicitly check for errors with json_last_error(), which should equal JSON_ERROR_NONE unless something went wrong.
If everything works fine, $obj will be an object, thus feeding echo with it will never yield anything useful:
echo $obj;
You might want to use var_dump() instead.
$json is a string. You should decode it first using json_decode($json)
Related
I want to parse values from an Json API, but I cant get it to work
The API returns this JSON:
[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]
I tried to get the ID value like this:
$json_obj = json_decode($resp);
print $json_obj->assets[0]->id;
but I get no result whereas it should be 6. What do I do wrong here?
Remember the outer part of the JSON is an array, as suggested by the opening [. So you need to first access the first (and only) element of it:
$json_obj[0]->assets[0]->id; //<-- note the first [0]
I think the correct answer is
$json_obj = json_decode($resp);
print $json_obj[0]->assets[0]->id;
The json object will be converted to a php array, since you have an array with a object inside in your case it will be a multidimentional array with the objects inside.
Try this its worked for me..
$json ='[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]';
$json_obj = json_decode($json);
var_dump($json_obj[0]->assets[0]->id)
?>
decode JSON to the array and fetch the id by proper array keys
$jToArray = json_decode($resp, TRUE);
echo $jToArray[0]['assets'][0]['id'];//You will get the correct id
i know it sounds so easy. just use foreach looping or json_decode, and you can retrieve json data.
yeah it was, until i got multiple array json when trying retrieving data from elasticsearch.
im confused how to retrieve this :
{
"took":3,
"status": "taken",
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total":2,
"msg":"ilusm",
"hits":
[
{
//goes here
"id":1234
},
{
//goes here
"id":4321
}
]
},
"date-created": "2016-06-06"
}
i use this to retrieve my first data :
$result = json_decode(json_encode($product),true);
echo "total took:";
echo $result['took'];
echo "total shards:";
echo $result['_shards']['total'];
the problem is,i cant retrieve data inside hits.
how can i retrieve hits id : 1234 ?
echo"view all total hits :";
echo $result['hits']['total'];
echo"view all total msg:";
echo $result['hits']['msg'];
echo"view hist data :";
echo json_decode(json_encode($result['hits']['hits']), true);
i got this error :
Message: Array to string conversion
please help me to fix this out.
many thanks in advance.
Try this it's work for me.
$result= '{"took":3,"status": "taken","_shards": {"total": 5,"successful": 5,"failed": 0},"hits": {"total":2,"msg":"ilusm","hits":[{"id":1234},{"id":4321}]},"date-created": "2016-06-06"}';
$array= json_decode($result, true);
echo $array["hits"]["hits"][0]['id']; //output 1234
output : 1234
$string = '{"took":3,"status": "taken","_shards": {"total": 5,"successful": 5,"failed": 0},"hits": {"total":2,"msg":"ilusm","hits":[{"id":1234},{"id":4321}]},"date-created": "2016-06-06"}';
$hits= json_decode($string, true);
$hits = $hits['hits']['hits'];
foreach($hits as $hitsIndex => $hitsValue){
if($hitsValue["id"] == '1234'){
var_dump($hitsValue["id"]);
}
}
I think you are a little confused about json & php data management.
Should you tell us what $product variable is? (string,object/array).
Usually you get json data as string and parse it to php variables with json_decode.
Your Javascript-like object declaration of $product is useless.
While answering Get JSON object from URL Difficulties, I noticed one of the JSON names was "$id":
{ "data" : [
{
"$id": "1",
"SearchKey": "Alnwick |Alnwick",
...
This caused the following php code to throw different errors:
$json = ... //json above
$obj = json_decode($json);
echo property_exists($obj->data[0], '$id'); // prints true
echo $obj->data[0]->$id; // PHP Fatal Error: Cannot access empty property ...
echo $obj->data[0]->id; // PHP Notice: Undefined property stdClass::$id ...
echo $obj->data[0]->'$id'; // PHP Parse Error: syntax error, unexpected ''$id'' (T_CONSTANT_ENCAPSED_STRING) ...
Assuming the json is decoded as objects not arrays, how can I access the "$id" field?
Accessing the variable via {'invalid-parameter-name'} works:
echo $obj->data[0]->{'$id'}; // 1
please help me how to parse following JSON in PHP.
I got following JSON using PIWIK reporting api. How do I get PageTitle from following json in PHP. I tried following code for JSON parsing.
$json = '[
{
"idSite": "1",
"idVisit": "84",
"visitorId": "f08dc1f2a3e1f839",
"visitorType": "returning",
"visitorTypeIcon": "plugins/Live/images/returningVisitor.gif",
"visitConverted": "0",
"visitConvertedIcon": null,
"visitEcommerceStatus": "none",
"visitEcommerceStatusIcon": null,
"searches": "0",
"events": "4",
"actions": "9",
"actionDetails": [
{
"type": "action",
"url": "http://mywwebsiteurl.com",
"pageTitle": "PageTitle",
"pageIdAction": "110"
}
]
}
]';
$visits = json_decode($json, true);
foreach ($visits->actionDetails as $data) {
echo $data->pageTitle;
}
I got following notice
Notice: Trying to get property of non-object
How to get pageTitle from above JSON.
It should be :-
$visits = json_decode($json, true);
foreach ($visits[0]["actionDetails"] as $data) {
echo $data["pageTitle"];
}
You set second attribute to TRUE - so according to the manual.
"When TRUE, returned objects will be converted into associative arrays."
Try using the array aproach
foreach ($visits['actionDetails'] as $data){
echo $data['pageTitle'];
}
As documented in the manual, and mentioned by Matt, the second parameter of json_decode() controls the return type. If it is omitted or set to false (the default) then an object is returned. If it is set to true an array is returned.
Your code, json_decode($json, true);, will return an array but you then try to use the array as an object.
I'm new to php and this has really stumped me - i'm trying to parse this json in order to get the value of match_id.
{
"result": {
"status": 1,
"num_results": 1,
"total_results": 500,
"results_remaining": 499,
"matches": [
{
"match_id": 649218382,
"match_seq_num": 588750904,
"start_time": 1399560988,
"lobby_type": 0,
"players": [
{
"account_id": 4294967295,
"player_slot": 0,
"hero_id": 69
}
]
}
]
}
}
So far I have:
$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
$matchid = $decodedmatchhistory->{'match_id'};
But I'm pretty sure that's not the right way to do it at all. All I need out of this JSON file is the match id.
You are getting an array back from json_decode() as you passed the second parameter with a value of true so you access it like any multi-dimensional
array:
$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
echo $decodedmatchhistory['result']['matches'][0]['match_id'];
Demo
Naturally if you have multiple matches you wish to get the match ID for you can loop through $decodedmatchhistory['result']['matches'] and get them accordingly.
This is your code:
$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
$matchid = $decodedmatchhistory->{'match_id'};
Two issues. First when you set true in a call to json_decode() that returns the results as an array:
When TRUE, returned objects will be converted into associative arrays.
So you would access the data as an array like this:
$matchid = $decodedmatchhistory['match_id'];
But your original syntax is incorrect even if you were accessing the data as an object:
$matchid = $decodedmatchhistory->{'match_id'};
If you set json_decode() to false or even left that parameter out completely, you could do this instead:
$decodedmatchhistory = json_decode($matchhistoryjson);
$matchid = $decodedmatchhistory->match_id;
So try both out & see what happens.