I'm trying to parse a JSON file using PHP and json_decode, however I'm having difficulting doing this when the JSON returned is namespaced. For example:
$json_ouput = json_decode($json);
foreach ( $json_ouput->feed as $feed) {
/*
Here is the problem, $feed contains a namespaced key
$feed->ab:test->value // Does not work :(
*/
}
Whats the best solution here?
Same as always.
$feed->{'ab:test'}->value
Much in the same way you would remove ambiguity between a variable and surrounding string characters, you can use { and } to patch together part of an accessor:
$json = '{"feed":[{"ab:test":{"value":"foo"}},{"ab:test":{"value":"bar"}}]}';
$json_output = json_decode( $json );
foreach ( $json_output->feed as $feed ) {
// Outputs: foo bar
print_r( $feed->{'ab:test'}->value );
}
Demo: http://codepad.org/MYYwOJj2
Related
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
?>
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);
}
}
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.
I'm trying to encode a json string but it keeps returning null. I've tried a few suggestion here on st
$url = "https://www.google.com/finance?output=json&start=0&num=200&noIL=1&q=[currency%20%3D%3D%20%22USD%22%20%26%20%28%28exchange%20%3D%3D%20%22NYSEMKT%22%29%20%7C%20%28exchange%20%3D%3D%20%22NYSEARCA%22%29%20%7C%20%28exchange%20%3D%3D%20%22NYSE%22%29%20%7C%20%28exchange%20%3D%3D%20%22NASDAQ%22%29%29%20%26%20%28change_today_percent%20%3E%3D%20-101%29%20%26%20%28change_today_percent%20%3C%3D%20-3%29%20%26%20%28volume%20%3E%3D%20150001%29%20%26%20%28volume%20%3C%3D%20313940000%29%20%26%20%28last_price%20%3E%3D%2010%29%20%26%20%28last_price%20%3C%3D%20229301%29]&restype=company&ei=T5mTVKG5IYT1igKEoYHQCQ";
$obj = file_get_contents($url);
$obj = json_decode($obj);
var_dump($obj);
JSON doesn't support \x escapes, so it's invalid JSON by definition, hence why json_decode() returns null. Decoding the valid JSON \u0022 works fine.
$url = "https://www.google.com/finance?output=json&start=0&num=200&noIL=1&q=[currency%20%3D%3D%20%22USD%22%20%26%20%28%28exchange%20%3D%3D%20%22NYSEMKT%22%29%20%7C%20%28exchange%20%3D%3D%20%22NYSEARCA%22%29%20%7C%20%28exchange%20%3D%3D%20%22NYSE%22%29%20%7C%20%28exchange%20%3D%3D%20%22NASDAQ%22%29%29%20%26%20%28change_today_percent%20%3E%3D%20-101%29%20%26%20%28change_today_percent%20%3C%3D%20-3%29%20%26%20%28volume%20%3E%3D%20150001%29%20%26%20%28volume%20%3C%3D%20313940000%29%20%26%20%28last_price%20%3E%3D%2010%29%20%26%20%28last_price%20%3C%3D%20229301%29]&restype=company&ei=T5mTVKG5IYT1igKEoYHQCQ";
$obj = file_get_contents($url);
$obj = trim($obj);
$obj = str_replace('\x', '\u00', $obj);
$obj = json_decode($obj,true);
var_dump($obj);
Try this code
<?php
function convert($string) {
return preg_replace_callback('#\\\\x([[:xdigit:]]{2})#ism', function($matches) {
return htmlentities(chr(hexdec($matches[1])));
}, $string);
}
$url = "https://www.google.com/finance?output=json&start=0&num=200&noIL=1&q=[currency%20%3D%3D%20%22USD%22%20%26%20%28%28exchange%20%3D%3D%20%22NYSEMKT%22%29%20%7C%20%28exchange%20%3D%3D%20%22NYSEARCA%22%29%20%7C%20%28exchange%20%3D%3D%20%22NYSE%22%29%20%7C%20%28exchange%20%3D%3D%20%22NASDAQ%22%29%29%20%26%20%28change_today_percent%20%3E%3D%20-101%29%20%26%20%28change_today_percent%20%3C%3D%20-3%29%20%26%20%28volume%20%3E%3D%20150001%29%20%26%20%28volume%20%3C%3D%20313940000%29%20%26%20%28last_price%20%3E%3D%2010%29%20%26%20%28last_price%20%3C%3D%20229301%29]&restype=company&ei=T5mTVKG5IYT1igKEoYHQCQ";
$obj = file_get_contents($url);
$obj = convert($obj);
$obj = json_decode($obj);
echo '<pre>'; print_r($obj); echo '</pre>';
?>
As recommended here (and pointed out by #showdev already, thanks!) you should use their RSS API and parse that as XML instead, because Google does not deem it necessary to honour web standards (here, they fail at JSON; elsewhere, they fail at simple things like SMTP and especially IMAP).
JSON has a very detailed specification, and it is very easy to adhere to in generators. Making JSON parsing strict is recommended for security reasons – especially with external input. So please use Google’s RSS variant.
I am attempting to write PHP code to interact with JSON output from Mapquest's Open API / Open Street Map service. I have listed it below. I have been using this code in my Drupal 6 implementation. This code returns no output. When I use it, json_last_error() outputs 0.
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode(var_export($json));
$foo .= $obj->{'fuelUsed'};
$output .= foo;
return $output;
}
You can view the raw JSON output by following the URL. In this function I am expecting to get 1.257899 as my output. I have two questions:
(1) What can I call so I get items out of my array. For instance, how can I get the value represented in JSON "distance":26.923 out of the array?
(2) Is it possible am I running into a recursion limit issue that I've read about in the PHP Manual?
If you read the manual page for json_decode carefully, you'll notice there is a parameter (false by default) that you can pass to have it return an array rather than an object.
$obj = json_decode($json, true);
So:
<?php
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json, true);
//var_dump($obj);
echo $obj['route']['fuelUsed'];
}
json_test_page();
Remove the var_export function from json_decode.
You're trying to convert information about a string to json.
I was able to get the fuelUsed property this way
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json);
return $obj->route->fuelUsed;
}