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)
Related
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
So I'm returning the data from twitter, and for some reason I cannot return the count data, all it returns when I echo it is the open curly bracket.. here is how I am trying to echo it.
"statuses": [],
"search_metadata": {
"completed_in": 0.008,
"max_id": 668543797022826500,
"max_id_str": "668543797022826503",
"query": "URL",
"refresh_url": "URL",
"count": 15,
"since_id": 0,
"since_id_str": "0"
}
That is what the code below returns.. all I am trying to do is echo the count data but it doesn't.. all it prints instead of the 15 is {
$counter = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$this->url );
$ajsn = json_encode($counter);
echo $ajsn['search_metadata']['count'];
Could anyone explain to me why this isn't printing?
try this:
$ajsn = json_decode($counter, true);
echo $ajsn['search_metadata']['count'];
When you run this:
$counter = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$this->url );
$ajsn = json_encode($counter);
echo $ajsn['search_metadata']['count'];
you get "{", you say.
That you get a single character should probably be expected because json_encode returns a string, not an array. And a key index into a string should get you an error, or at least a warning; if it doesn't, it probably returns the integer equivalent of the string, which is zero. So you're getting the zeroth (the first) character of a JSON encoding.
That it is a "{" is actually good news. It means that json_encode did return something: the curly brace is the opening of a JSON object.
What you should do is verify what {$counter} is. Is it an object? An array? Then you can echo it appropriately. For example $counter->search_metadata->count.
Otherwise, since $ajsn is a valid string, a quick and dirty ugly fix is to convert it to an array again:
$counter = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$this->url );
$ajsn = json_encode($counter); // Convert whatever to string
$ajsn = json_decode($ajsn, true); // Convert ajsn to associative array
echo $ajsn['search_metadata']['count'];
Also, activate all error and warning output. You should have gotten something to tell you where you stood, and you got nothing - that can make debugging needlessly complicated. Activate screen display or at the very least file logging using error_reporting and the appropriate php.ini settings.
I am trying to get json data from the Statcounter API.
I have the following:
$query = makeQuery("2292634", "demo_user", "statcounter", "visitor", "");
echo $query . "<br>";
$response = file_get_contents($query, true);
$data = json_decode($response, true);
echo $data['sc_data']['log_visits'];
I know the query is correct, and I know the $response is filled with unformatted json. The trouble is accessing the array and pulling the values out.
Here are the first couple lines of the unformatted json it is giving me.
This link will only work for 15 minutes, I can generate a new one if you would like to see the raw json.
http://api.statcounter.com/stats/?vn=3&s=visitor&pi=2292634&t=1398791335&u=demo_user&sha1=c6cdfd6c84227801c6ca758c17252712e3f76514
{"#attributes":{"status":"ok"},"sc_data":[{"log_visits":"1","entries_in_visit":"2","entry_t":"2014-04-29 17:57:33","entry_url":"http:\/\/www.guitar-online.com\/en\/","entry_title":"Learn how to play the guitar: tutorials, guitar
Obviously I am not accessing the array in the correct way...but I haven't found the syntax to make it work YET!
Thank you for your help.
Looking at your data, sc_data is an array containing nested JSON objects so you should be able to iterate over that array to read the data like you want:
echo $data['sc_data'][0]['log_visits'];
The code above will access the first element of the array sc_data and print the value of log_visits
When you have {"field":['a','b','c']} in JSON, you would access 'a' as field[0].
The elements of the array can be any valid value, i.e.
string
number
object
array
true
false
null
In your case it is objects and you access that object the same way you would access any other array element - by the index number (JSON doesn't have associative array of type "key" => "value")
[{"text":"\n $3.99\n ","attrs":{"class":"priceLarge"}}]
This is how JSON is being returned to me... (using print_r($price) to display)...
I have tried various ways in PHP to access this data, but nothing has worked.
I want the "text"...
Thanks!
EDIT:
var_dump (as requested)
string(96) "[{"text":"\n $3.99\n ","attrs":{"class":"priceLarge"}}]"
Make use of json_decode()
<?php
$jsonStr='[{"text":"\n $3.99\n ","attrs":{"class":"priceLarge"}}]';
$jsonArr = json_decode($jsonStr);
echo $jsonArr[0]->text;
Assuming that you've got a JSON string, you need to use json_decode() to translate it into a PHP object first:
$json = json_decode($jsonString);
From there, you can access text from the first object in the data (which is an array, defined by the outer square brackets[]:
echo $json[0]->text;
// | |
// | The property text of that first element.
// |
// The first element in the array of data.
$string = '[{"text":"\n $3.99\n ","attrs":{"class":"priceLarge"}}]';
$obj = json_decode($string);
Allowing you to access:
print $obj[0]->text;
I'm trying to get the "screenshotUrls" string from this piece of json:
$request_url = 'http://itunes.apple.com/search?term=ibooks&country=us&entity=software&limit=1';
$json = file_get_contents($request_url);
$decode = json_decode($json, true);
echo $decode['results'][0]['screenshotUrls'];
But I get only text "Array"
What have I done wrong?
Try
var_dump($decode['results'][0]['screenshotUrls']);
IF you get 'Array' output by PHP that means that you're trying to echo an actual array (or the string 'Array'...). That means you need to get a specific index value.
Since $decode['results']['0']['screenshotUrls'] is an array, if you want just a string (say, delimited by commas), you could use
echo implode(",", $decode['results']['0']['screenshotUrls']);
This will iterate over the array, and return a comma-separated string of all the URLs.
Do a var_dump($decode['results']['0']['screenshotUrls']). You'll find that the ['screenshotUrls'] is actually an Array, containing one or more URLs (hence the plural 'urls' in its name).
There's nothing wrong with your code so far, but $decode['results'][0]['screenshotUrls'] is an array of all the URLs to screenshots. To go through each one individualy, you need to do:
forearch ($decode['results'][0]['screenshotUrls'] as $url) {
// Do stuff here
}