PARSE json string to json array (from GET) - php

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.

Related

How to parser Json result from base64_encode() in PHP

I have written a php script to decode a value using base64_decode() function. I want to store the parse the result into different variable. How do I achieve this??
$str = 'eyJ0eXAiO0IjoiNTAwMCIsInZhbGlkaXR5IjoiMzAifQjdubnmGHANidodnd';
$msisdn_64 = base64_decode($msisdn);
print_r($msisdn_64);
NB: For privacy sake the $str variable contains dummy value And this Does not use a token to decode
The code above outputs:
{"typ":"JWT","alg":"HS256"}{"sub":"456564685455","service":"000","created":20010809,"account_name":"Acct","iss":"Acft","exp":false,"amount":"000","validity":"30"}}�.'���A˕X=·&|�L�0�"����
I tried something like this $msisdn[1]->sub , $msisdn[0]->sub , and $msisdn->sub to the value in the second object but its not working. Please help
You can use the json_decode function
https://www.php.net/manual/en/function.json-decode.php
Example:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
$str = 'eyJ0eXAiO0IjoiNTAwMCIsInZhbGlkaXR5IjoiMzAifQjdubnmGHANidodnd';
$msisdn_64 = base64_decode($msisdn);
print_r($msisdn_64);
Here you need to decode the string again like below.
$str = 'eyJ0eXAiO0IjoiNTAwMCIsInZhbGlkaXR5IjoiMzAifQjdubnmGHANidodnd';
$msisdn_64 = json_decode(base64_decode($msisdn),true);
print_r($msisdn_64);
remember to put the parameter true in json_decode() method, because it returns the result as an associative array.

PHP get curl array results from inside a key value

I'm trying to get the access_token value from a curl response. The key value which is [0] renders out like so, {"access_token":"430f8a7d4f721a9e51e3558689ff28ec592923d2","expires_in":3600,"token_type":"Bearer","scope":null}.
However, I just need the value nested inside of access_token, which is 430f8a7d4f721a9e51e3558689ff28ec592923d2.
The output is rendered using this:
$cmd="curl -u testuser:123456 http://localhost/oauth2/server/token.php -d 'grant_type=client_credentials'";
exec($cmd,$result);
echo '<pre>'; print_r($result[0]); echo '</pre>';
How might go about doing this?
Btw, none of this is sensitive data. I'm just experimenting with oauth2.
Use the json_decode function on the results.
<?php
$json = '{"access_token":"430f8a7d4f721a9e51e3558689ff28ec592923d2","expires_in":3600,"token_type":"Bearer","scope":null}';
// Decode the JSON into an object
$decodedJson = json_decode($json);
$accessToken = $decodedJson->access_token;
var_dump($decodedJson,$accessToken);
// Decode the JSON into an array (note the true on the decode)
$decodedJson = json_decode($json,true);
$accessToken = $decodedJson['access_token'];
var_dump($decodedJson,$accessToken);
Encoding the json result, finds the subset.
$json = $result[0];
$json = json_decode($json, true);
echo $json['access_token'];

how to fetch json fom url in 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

PHP json_Encode an array of json_encode-ed arrays

Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode

Reading multiple json values with php

I am trying to read certain values from a json string in php, I am able to do a simple json string with only one value such as
$json = '{"value":"somevalue"}';
Using this:
<?php
$json = '{"value":"somevalue"}';
$obj = json_decode(json_encode($json));
print $obj->{'value'};
?>
But when i try an get a value from the following json string it throws an error...
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
I validated the json on JSONlint but not sure how to access the values within this with php.
Thanks
You can try this:
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
//since $json is a valid json format you needn't encode and decode it again
$obj = json_decode($json);
print_r($obj->filed);
print_r($obj->rule);
You can pass true as a second parameter to json_decode() to get the results as an array
$my_arr = json_decode($json, true);
var_dump($my_arr);
Should help you. You can then step through the array as you would normally.
use var_dump to print out the object with all it's members and hierarchy. you should then be able to find the value you are looking for

Categories