Foreach array loop for JSON - php

Here is my PHP/JSON code:
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$decoded= json_decode($json);
$data=$decoded->matches[0];
foreach ($data as $value) {
print_r($value->team1->logo_url);
}
Now I have the following problem
Notice: Trying to get property of non-object
and
Notice: Undefined property: stdClass::$team1
I just want use foreach loop and then show my results in HTML.
Why I am getting the 2 mentioned problems and how can I show the correct results?

Ok so the url your are using return VALID JSON, no need to change any of it!
I suggest using arrays, it has always appeared simpler to me
Do you want the logo_url from team or image_url from league? I will show both in my implementation.
So here is some corrected code
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded= json_decode($json,true); // True turns it into an array
$data = $decoded['matches'];
foreach ($data as $value) {
//I am not sure which one you want!!!
echo $value['league']['image_url'] . "<br>";
echo $value['team1']['logo_url'] . "<br>";
echo $value['team2']['logo_url'] . "<br>";
}
*EDIT To show wanted implementation by questions author...
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded= json_decode($json,true); // True turns it into an array
$data = $decoded['matches'];
foreach ($data as $value) {
echo "
<img src=\"http://dailydota2.com/{$value['team1']['logo_url']}\">
<img src=\"http://dailydota2.com/{$value['team2']['logo_url']}\">
";
}

I have checked your code and have some notes and hopefully a solution:
1- You are trying to get non existing key from JSON data, that is the message telling you.
2- I am still not sure what do you get from the JSON API. But regarding to dailydota2 documentation there is nothing called image_url under team1. I guess you are looking for logo_url or something like that.
3- Do not change the format of JSON as you do in your code, therefore delete following line:
$json=str_replace('}, ]',"} ]",$json);
Just leave the main JSON output from API as default.
4- When you try to get specific key from the decoded JSON/Array just use following way:
$data = $decoded->{'matches'};
in stead of
$data=$decoded->matches[0];
Reference: http://php.net/manual/en/function.json-decode.php
5- And finally your foreach loop is working but needs the correct key:
foreach ($data as $value) {
print_r($value->team1->logo_url);
}
When all these step is done, it should works.
Here is your final corrected code:
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded = json_decode($json);
$data = $decoded->{'matches'};
foreach ($data as $value) {
print_r($value->team1->logo_url);
echo '<img src="http://dailydota2.com/' . $value->team1->logo_url . '">';
}
It returns following output, and I do not get any errors.
/images/logos/teams/cdecgaming.png/images/logos/teams/teamempire.png
/images/logos/teams/ehome.png/images/logos/teams/ehome.png
/images/logos/teams/fnatic.png/images/logos/teams/cloud9.png
/images/logos/teams/teamissecret.png/images/logos/teams/teamissecret.png
/images/logos/teams/natusvincere.png/images/logos/teams/fnatic.png
Again I really do not know which information you want to get from the API but here you have a base of working code that you can work further with to get the required data from the right KEYs.

Related

How to access specific value in php and json

I'm using a token:
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
and here's the json text(not everything);
{
"success":true,
"data":[{
"id":1,
"creator_user_id":{
"id":1682756,
"name":"Kamilah",
"email":"kamilah#fractal.ae",
"has_pic":false,
"pic_hash":null,
"active_flag":true,
"value":1682756},
"title":"FFS Organization deal"
}]
}
I wanted to display "title" and I always get an error
Notice: Undefined index: creator_user_id in
C:\xampp\htdocs\pipedrive\getjson.php on line 8
Here's my code so far:
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
$response = file_get_contents($url);
$object = json_decode($response, true);
echo $object['data']['creator_user_id']['title'];
I'm new to json so I'm just practicing and trying to figure out how to echo a specific value in php. Would be appreciated if you can explain exactly how it works when you echo from json to php.
Thank you! :)
First of all you need to debug the array after using json_decode().
<?php
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
$response = file_get_contents($url);
$object = json_decode($response, true);
echo "<pre>";
print_r($object); // this will print all data into array format.
?>
As per this array, you do not have title index inside the creator_user_id array. title is a separate index.
Also note that, $object['data'] containing two indexes not one. you can get title as:
<?php
foreach ($object['data'] as $key => $value) {
//print_r($value); // this will print the values inside the data array.
echo $value['title']."<br/>"; // this will print all title inside your array.
}
?>
Result:
FFS Organization deal
Google deal

Json api decoding

here is my json
{
"rgInventory": {
"5455029633": {
"id":"5455029633",
"classid":"310776543",
"instanceid":"302028390",
"amount":"1"
}
}
}
Here is my way to parse json in php
$content = file_get_contents("http://steamcommunity.com/profiles/76561198201055225/inventory/json/730/2");
$decode = json_decode($content);
foreach($decode->rgInventory->5455029633 as $appid){
echo $appid->id;
}
I need to get that 5455029633 but it dont work in foreach.
And I want to store it in the variable too.
Json, which you've provided is invalid. Remove last comma from "amount":"1", and you are missing closing curly bracket. Then you should be able to access desired value as $decode->rgInventory->{"5455029633"}.
Or make your life simpler ;) and just go for assoc array $decode = json_decode($content, true);
You will need to pass true as second argument to the function json_decode to get an array instead of an object :
PHP
<?php
$content = file_get_contents("http://steamcommunity.com/profiles/76561198201055225/inventory/json/730/2");
$decode = json_decode($content, true);
echo $decode['rgInventory']['6255037137']['id']; // will output the property 'id' of the inventory 6255037137
$invetory = $decode['rgInventory']['6255037137'] // will store the inventory 6255037137 in the variable $inventory
?>

Decode JSON to PHP

I have a .txt file called 'test.txt' that is a JSON array like this:
[{"email":"chrono#gmail.com","createdate":"2016-03-23","source":"email"}]
I'm trying to use PHP to decode this JSON array so I can send my information over to my e-mail database for capture. I've created a PHP file with this code:
<?php
$url = 'http://www.test.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
echo $json;
?>
For some reason, it's not echoing the decoded JSON when I visit my php page. Is there a reason for this and can anyone shed some light? Thanks!
You use echo to print scalar variables like
$x = 'Fred';
echo $x;
To print an array or object you use print_r() or var_dump()
$array = [1,2,3,4];
print_r($array);
As json_decode() takes a JSON string and converts it to a PHP array or object use print_r() for example.
Also if the json_decode() fails for any reason there is a function provided to print the error message.
<?php
$url = 'http://www.test.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
if ( json_last_error() !== JSON_ERROR_NONE ) {
echo json_last_error_msg();
exit;
}
You'll need to split that json string into two separate json strings (judging by the pastebin you've provided). Look for "][", break there, and try with any of the parts you end up with:
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}

Errors with json_decode in php

We are have json:
{ "list":
[
{"id":"4045","value":"Xin Kai"},
{"id":"4141","value":"YZK"},
{"id":"4099","value":"ZX"}
]
}
For get value we use next code:
$json = json_decode($result, true);
foreach($json['list'] as $item) {
print $item['value'].'<br />';
}
But now we get error: Warning: Invalid argument supplied for foreach()...
Tell me please where error in code and how will be right?
Your issue is that you're doing this in your code:
foreach($json->list as $item) {
When you should be doing this:
foreach($json['list'] as $item) {
As you decoded it as an array and not as an object.
Read More: json_decode()
Also, as zerkms said,
>>> windows-1251 <<< JSON document must be in UTF-8
Before json_decode you need get json in utf-8, in you exmple(if you get json in windows-1251) you need use next code:
EXAMPLE FIRST - if you want get array
//if you want get array
$json_obj = json_decode(iconv("windows-1251","utf-8",$result), true);
foreach($json_obj['list'] as $item) {
print $item['value'].'<br />';
}
EXAMPLE SECOND - if you wnt get object
//if you wnt get object
$json_obj = json_decode(iconv("windows-1251","utf-8",$result));
foreach($json_obj->list as $item) {
print $item->value.'<br />';
}
Enjoy!

How do I access a JSON-property of a JSON-Object in php?

I've got a really weird problem and I can't figure out why.
The situation is quite simple. My Android app uploads JSON data to a php script on my server. Right now I am trying to parse the data.
This is the JSON-Array passed to the script (via httpPost.setEntity ()):
[{"friends_with_accepted":"false","friends_with_synced":"false","friends_with_second_id":"5","friends_with_first_id":"6"}]
This is the php script:
<?php
// array for JSON response
$response = array();
$json = file_get_contents ('php://input');
$jsonArray = json_decode ($json, true);
foreach ($jsonArray as $jsonObject) {
$firstId = $jsonObject['friends_with_first_id'];
$accepted = $jsonObject ['friends_with_accepted'];
$secondId = $jsonObject ['friends_with_second_id'];
$synced = $jsonObject ['friends_with_synced'];
echo "accepted: ".$accepted."synced: ".$synced;
} ?>
And this is the response I get from the script:
accepted: synced: false
Why is the "synced" property correctly passed, but not the "accepted" property??
I can't see the difference. Btw, firstId and secondId are parsed correctly as well.
Okay, i just found the problem:
Instead of
$accepted = $jsonObject ['friends_with_accepted'];
I deleted the space between jsonObject and the bracket
$accepted = $jsonObject['friends_with_accepted'];

Categories