how to fetch json fom url in php - php

I am trying to make a php page tp print json data for this i m using one paraeter for which i needed to fetch json from another url.I used the code given in other stackoverflow ans but it always giving 0.I tried everything but it always giving 0.My php code is:
<?php
if(isset($_POST['add']))
{
require_once('loginConnect.php');
$bookname=$_POST['bookname'];
$url = "http://example/star_avg.php?bookName=$bookname";
$json = file_get_contents($url);
$json_data = json_decode($json,TRUE);
echo 'data' + $json_data->results[0]->{'num'};
?>
My json data from other url is:
{"result":[{"avg":"3.9","num":"3"}]}

You see 0 printed because you're performing an addition + between the string data and a non-existent property. In PHP, to concatenate strings, do not use +; instead, use the dot . operator
In addition, because you're using true as the 2nd parameter to json_decode, what you get back is an array of arrays. Use the array notation [] rather than the object notation -> to access members.
$json_data = json_decode($json,TRUE);
$num = $json_data['result'][0]['num']; //<- array notation
echo 'data: '.$num; //prints data: 3
Live demo

Related

PHP check JSON string for item = value

I need to get the value one one particular value in my json string
the json string comes from an api url http://url:port/api.php?action=reg_user&sub=list and outputs like so
[{"id":"1","username":"username1","credits":"0","group_id":"1","group_name":"Administrators","last_login":"1511883014","date_registered":"1421604973","email":"test1#my-email.com","ip":"8.8.8.8","status":"1"},{"id":"31","username":"username2","credits":"0","group_id":"1","group_name":"Administrators","last_login":"1539813642","date_registered":"1473632400","email":"test2#my-email.com","ip":"8.8.8.8","status":"1"},
i would like to check the value of credits where username = username1
then if credits > 30 do x, else do y
I presume first of all I need to decode this jason string
so i tried to do
$api_result = file_get_contents( 'http://url:port/api.php?action=reg_user&sub=list' );
$json_decode = json_decode($api_result);
echo $json_decode;
expecting this to echo the array in a nicely formatted structure, instead it just outputs the word Array. Where do I go from here?
Thanks
UPDATE 1...
SO i checked again and I defo can echo $api_result so I know that the file_get_contents is working fine i tried the two comments suggestions however both didn't work...
one of the suggestions was to make my php
$api_result = file_get_contents( 'http://url:port/api.php?action=reg_user&sub=list' );
$json_decode = json_decode($api_result);
echo $json_decode['username'];
here is a screenshot of how the echo $api_result is formatted in case this isnt a propper json string
so to me this looks like it opens with (and is all contained in a pair of [] and then each result is enclosed in {} as I'd expect with a json string right? however i thought json strings used {} and arrays used {} so to me this looks like a string inside an array???
I looked at php.net's resource on JSON DECODE and tried var_dump(json_decode($json)); which did print me this
UPDATE 2
I just tried https://www.functions-online.com/json_decode.html and pasted the data in, it was able to decode the data absolutely fine,
It then gave me a copy if the json_decode sample at the bottom but this didn't work either, returning a null value like json_decode doesn't work on my server?
From your second screenshot (please cut & paste the text instead!) you can see the decoded JSON is an array of objects with properties id, username etc. So you can access them using object notation. This code uses the snippet of your api_result from your original question to demonstrate how to do what you want:
$api_result = '[{"id":"1","username":"username1","credits":"0","group_id":"1","group_name":"Administrators","last_login":"1511883014","date_registered":"1421604973","email":"test1#my-email.com","ip":"8.8.8.8","status":"1"},{"id":"31","username":"username2","credits":"0","group_id":"1","group_name":"Administrators","last_login":"1539813642","date_registered":"1473632400","email":"test2#my-email.com","ip":"8.8.8.8","status":"1"}]';
$json = json_decode($api_result);
foreach ($json as $user) {
if ($user->username == 'username1') {
if ($user->credits > 30) {
// do x
echo "user $user->username has more than 30 credits ($user->credits)";
}
else {
// do y
echo "user $user->username has less than or equal to 30 credits ($user->credits)";
}
}
}
Output:
user username1 has less than or equal to 30 credits (0)

PARSE json string to json array (from GET)

i'm tring to parse url's json string to an json array.
ISSUE: json_decode = empty
QUESTION: Does anyone see what am i doing wrong?
MY STEPS:
tests from browser:
.....send.php?{"contactName":"name1"},{"contactName":"name2"}
my php code:
1. $url = $_SERVER['QUERY_STRING'];
2. $urlStringDecoded = urldecode($url);
echo urlStringDecoded result ok:
{"contactName":"name1"},{"contactName":"name2"}
3. $json = json_decode($urlStringDecoded, true);
RESULT EMPTY
echo("$json");
Seems like your JSON is invalid. Wrap your current string within [ ] Brackets.
Eg.
<?php
$url = $_SERVER['QUERY_STRING'];
//echo $url;
$urlStringDecoded = urldecode($url);
echo $urlStringDecoded;
$json = json_decode("[".$urlStringDecoded."]", true);
echo "<pre>";
print_r($json);
echo "</pre>";
?>
As you are trying to convert json string to json, you should provide right format. From you example it looks like you are passing , comma separated json objects whereas it should be an array. Add [] around your string and then try, in other words make it an array.

get data from json array in php

I am having trouble accessing information in a json-Array that I retrieved using php's json_decode function.
the json-file looks as follows:
{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":XXX,"currencySign":"€","email":"X.X#X.com","code":0}]},"result":"success"}
I used the following php code to get the contents:
$json = file_get_contents($json_url);
$data = json_decode($json,true);
echo '<pre>' . print_r($json, true) . '</pre>';
The result print_r displays looks just like what I expect and looks like the json.
However, I cannot figure out to access the variables. Whenever I try something like
$test = $json['model']['results']['balance'];
the script throws an error, which I can't identify. I already figured out if I access the $json variable like so:
$test = $json[n]; // returns the nth character, e.g. n = 0 $test = "{", n = 2 $test = "c"
The script also did not throw an error if I tried accessing the variable like so:
$test = $json['code']; // returns "{"
Can someone help me figure out how to navigate this array?
Thanks!
The results key is a true array, not an unordered map (key/value). Additionally, you should be accessing the decoded $data, not the $json string.
This should work for you:
$test = $data['model']['results'][0]['balance'];
This is what should have tipped you off:
{"results":[{"message"
^ ^
| |
| \-- Start of an array
|
\-- Start of an object
You recieve an error similar to Cannot use object of type stdClass as array in (...) right?
json_decode returns an object of the type stdClass which is the only object in php (as far as I know) which properties cannot be accessed like an array. You will have to access them as follows:
$json = '{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":"XX","currencySign":"€","email":"X.X#X.com","code":0}]},"result":"success"}';
$obj = json_decode($json);
var_dump($obj->message); //works
var_dump($obj["message"]); //throws exception
There is an error in the JSON array. "firstDepositDate": XXX is not a valid value. Should be a string "XXX".
Also you are trying to the wrong variable. The decoded data should be a PHP array. In this case $data['code'] instead of $json['code']

Use php variable index for retriving data from json

This is my json.
In php
$json = json_decode($finalAppData, true); // decode the JSON into an associative array
//suppose this is $link = ['appInfo']['items'][0]['screen']['items'][0]['screen']['items'][0];
This code is not working.
echo $json .$link."['screen']['menuHeader']";
produces output as
Array['appInfo']['items'][0]['screen']['items'][0]['screen']['items'][0]['screen']['menuHeader'].
but i want text value that can be seen if i use simply
echo $json['appInfo']['items'][0]['screen']['items'][0]['screen']['items'][0]['screen']['menuHeader'];
How can use index which is stored in variable to output data from json in php.
This should be similar to what you want:
$json = json_decode($finalAppData, true);
$link = "['appInfo']['items'][0]['screen']['items'][0]['screen']['items'][0]";
# Method #1
eval("echo \$json${link}['screen']['menuHeader'];");
# Method #2
$item = "\$json${link}";
eval("echo ${item}['screen']['menuHeader'];");
eval() takes a string of PHP code and interprets it. In this case, the nested keys are stored as a string in $link and then concatenated with a string that will be interpreted into the $json array resulting in a string of PHP code that will be sent to eval() to be interpreted.

PHP json_decode return empty array

I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));

Categories