How to parser Json result from base64_encode() in PHP - 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.

Related

PHP: Accessing dictionaries from a JSON string

I'm writing a simple PHP script that makes an API call that returns JSON. However, I'm having trouble figuring out how to take that JSON string, convert it into a dictionary, and access nested dictionaries/data within it.
Here's what I have so far:
<?php
$id = $_REQUEST['id'];
$url = http://exampleURLThatReturnsJSONString.com
$rawData = file_get_contents($url);
I've read that you should use something like $decodedData = json_decode($rawData)
, but I'm not sure what to do next, especially if I want to access nested dictionaries with a key like Schedule.
Any help would be greatly appreciated, thanks!
json_decode($json, $assoc = false) converts the json string into an object by default, or into an array if you specify $assoc = true
If you have $assoc = false then you must access the values by $decoded_data->key. Whereas if you have $assoc = true then you can do $decoded_data['key']
You can just access the decoded data like this:
echo $decodedData['key'];
This wil echo the value of the item in the dictionary with key 'key'. Nested values can be accessed like this:
echo $decodedData['key1']['key2']['...'];
You can always use var_dump to show what's inside the result. Also, read the documentation on json_decode for more information.
json_decode return array or object to which access is like to array.
http://php.net/manual/en/function.json-decode.php

how to use JSON.stringify and json_decode() properly

Im trying to pass a mulitidimensional Javascript array to another page on my site by:
using JSON.stringify on the array
assigning the resultant value to an input field
posting that field to the second page
using json_decode on the posted value
then var_dump to test
(echo'ing the posted variable directly just to see if it came through
at all)
Javascript on page one:
var JSONstr = JSON.stringify(fullInfoArray);
document.getElementById('JSONfullInfoArray').value= JSONstr;
php on page two:
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
The echo works fine but the var_dump returns NULL
What have I done wrong?
This got me fixed up:
$postedData = $_POST["JSONfullInfoArray"];
$tempData = str_replace("\\", "",$postedData);
$cleanData = json_decode($tempData);
var_dump($cleanData);
Im not sure why but the post was coming through with a bunch of "\" characters separating each variable in the string
Figured it out using json_last_error() as sugested by Bart which returned JSON_ERROR_SYNTAX
When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.
json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
Thanks to #Thisguyhastwothumbs
When you use JSON stringify then use html_entity_decode first before json_decode.
$tempData = html_entity_decode($tempData);
$cleanData = json_decode($tempData);
You'll need to check the contents of $_POST["JSONfullInfoArray"]. If something doesn't parse json_decode will just return null. This isn't very helpful so when null is returned you should check json_last_error() to get more info on what went wrong.
None of the other answers worked in my case, most likely because the JSON array contained special characters. What fixed it for me:
Javascript (added encodeURIComponent)
var JSONstr = encodeURIComponent(JSON.stringify(fullInfoArray));
document.getElementById('JSONfullInfoArray').value = JSONstr;
PHP (unchanged from the question)
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
Both echo and var_dump have been verified to work fine on a sample of more than 2000 user-entered datasets that included a URL field and a long text field, and that were returning NULL on var_dump for a subset that included URLs with the characters ?&#.
stripslashes(htmlspecialchars(JSON_DATA))
jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);`
I don't how this works, but it worked.
$post_data = json_decode(json_encode($_POST['request_key']));

How to decode the following code in Json?

I'm trying to decode the following JSON using php json_decode function.
[{"total_count":17}]
I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:
https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22
PHP's json_decode returns an instance of stdClass by default.
For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:
$var = json_decode('[{"total_count":17}]', true);
After that, you can access the variable as $result[0]['total_count']
See this JS fiddle for an example of how to read it:
http://jsfiddle.net/8V4qP/1
It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:
<?php
$result = json_decode('[{"total_count":17}]', true);
print $result[0]['total_count'];
?>
if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.
$json = "[{\"total_count\":17}]";
$arr = Jason_decode($json);
foreach ($arr as $obj) {
echo $obj->total_count . "<br>";
}
Or use json_decode($json, true) if you want associative arrays instead of objects.

How to parse JSON string in php

I'm getting below JSON response:
[{"startDate":"2012-07-12 11:21:38 +0530","totalTime":0},{"startDate":"2012-07-11 11:27:33 +0530","totalTime":0},{"startDate":"2012-07-16 18:38:37 +0530","totalTime":0},{"startDate":"2012-07-17 14:18:32 +0530","totalTime":0}]
i want make array of start date and totalTime, i have used these two lines but it wont work $obj, please suggest..
$obj = json_decode($dateTimeArr);
$dateAr = $obj->{'startDate'};
As everyone said, and you did - use json_decode.
$dateArrays = json_decode($dateTimeArr, true); // decode JSON to associative array
foreach($dateArrays as $dateArr){
echo $dateArr['startDate'];
echo $dateArr['totalTime'];
}
In future, if you are unsure what type or structure of data is in the variable, do var_dump($var) and it will print type of variable and its content.
It is very easy:
$Arr = json_decode($JSON, true);
json_decode() will give you nested PHP types you can then descend to retrieve your data.
use json_decode($json_response,true) to convert json to Array
Guess what you are looking for is json_decode()
Check out http://php.net/manual/en/function.json-decode.php for the inner workings

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