valid json doesnt work - php

I am trying to decode a JSON string in PHP,but somehow the json_decode doesnt like my string, i think it is not valid json. The thing that is very strange to me is, that if i put the json response in a variable manually, it is working. If i write the json response out in the browser, and i write the content of the variable, both are completely the same, like this:
{"id":455463,"Created":"2016-04-30T14:20:38.09","SenderCompanyName":"x","InvoiceNumber":"2555","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}
If i look in the webpage source, the content is also completely the same. I have also tryed to convert to UTF8, but no change.
How do you guys usually debug this, or what did i forget ?
code:
// calling web service and saving json response in variable
$json_response = CallAPI($method, $url, $json_request);
// the response contain some unvalid character in the end, so i am removing it
$json_response = substr($json_response, 0, strpos($json_response, "}"));
// trying to decode it, IT PRINTS OUT NULL
var_dump(json_decode($json_response, true));
// copying the json response from the above and putting it into a variable
$json_response = '{"id":455433,"Created":"2016-04-30T12:55:12.313","SenderCompanyName":"x","InvoiceNumber":"2525","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}';
// trying to decode it, IT PRINTS OUT THE RESULT SUCCESFULLY
var_dump(json_decode($json_response, true));

Try this:
<?php
$json = '{"id":455463,"Created":"2016-04-30T14:20:38.09","SenderCompanyName":"x","InvoiceNumber":"2555","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}';
var_dump(json_decode($json));
?>

I finally found the solution.
I had forget to add this in my CURL OPTIONS:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
After adding this, its working fine

Related

JSON string returned from test site includes extra characters preventing json_decode from working

I'm trying to learn about transferring data between servers. There is a test API on line containing json data. I tried the following:-
<?php
// Initiate curl session in a variable (resource) $curl_handle = curl_init();
$url = "http://dummy.restapiexample.com/api/v1/employees"; // website sample API data
// Set the curl URL option curl_setopt($curl_handle, CURLOPT_URL, $url);
// This option will return data as a string instead of direct output curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
// Execute curl & store data in a variable $curl_data = curl_exec($curl_handle);
curl_close($curl_handle);
// Write the JSON string
// echo $curl_data; // the above writes the JSON string ok
// Now try decoding to PHP array
$character = json_decode($curl_data);
echo $character[1]->employee_name;
// this throws an error 'Error: Cannot use object of type stdClass as array in C:\wamp64\www\curlex\curlget.php on line 24'
?>
The string returned has the following content (stripped down to 2 entries for clarity):-
{"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""},{"id":"2","employee_name":"Garrett Winters","employee_salary":"170750","employee_age":"63","profile_image":""}]}
I imagine json_decode fails because of the {"status":"success","data":preamble? How can this be resolved please?
Your problem is, that you have ommited the second parameter from json_decode() function, which if not set, will parse the string to an object, instead of an array.
You can find the documentation for this function here, what you are looking for it in your case, is the assoc parameter.
On the other hand, the example you show returns the sought employee_name inside another property, and not in the main property (namely data).
Try providing true as the second parameter to the function:
$character = json_decode($curl_data, true);
echo $character[1]['employee_name'];
But this will only work, if the example of the data is not accurate. If that example is accurate, to get the employee_name of the second data element, use:
$character = json_decode($curl_data, true);
echo $character['data'][1]['employee_name'];
Note, that php arrays are zero based, so if you want to get the first element out of an array, you should refer to it's 0th property.
You can access it like this:
$character = json_decode($curl_data);
echo $character->data[1]->employee_name;
Thanks to all who offered help. I hadn't realised that the returned string resulted in a two-dimensional array. I was misled by the web site which gave me the link to the freely available test data.

json_decode() returns null, even though file_get_contents() works perfectly, even though json is valid

Hi everyone i am reading some data from a txt-file with php using
file_get_contents('../../Datafiles/allThreads.txt');
this returns the following string
[{"OP":"ding","threadName":"","content":"","ID":6}]
when i try to vaildate with lint, I have no issues, so the json is valid.
But the problem is that when i call json_decode it keeps returning null:
$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');
Why is this happening? im following all the rules?
You can do it like:
//storing json contents in a variable.
$json_contents = file_get_contents('../../Datafiles/allThreads.txt');
//decode json
$currentThreadasList = json_decode($json_contents, TRUE)
Edit-1:
Have you tried the following:
$currentThreadasList = json_decode(file_get_contents('../../Datafiles/allThreads.txt'), TRUE);
Well, this piece of code
$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');
doesn't work because the first parameter to json_decode needs to be a JSON string, not a path. Just pass the content of the file as parameter like:
$yourJsonDecodedArray = json_decode(file_get_contents('../../Datafiles/allThreads.txt'), TRUE);

php return json encoded string from function

One of my functions is returning json encoded content using:
return json_encode($json, true);
Now in my code, calling this function I've already tried to use:
die(var_dump($result[0]));
die(var_dump($result["user"]));
die(var_dump($result->user));
None of this worked.
When I dump the whole content I get returned, this is the output:
{"usd":1,"user":10000}
I am assuming that the $result variable is the content that is returned from the function.
You cannot access the properties inside that json string, before you decode it again. Therefore you will not be able to use $result["user"] or $result->user as the result contains a json string.
You need to decode it first:
$result = json_decode($result, true);
http://php.net/manual/en/function.json-decode.php

How to display a JSON object with php and cURL?

I'm very new to php (I know next to nothing, in fact) and I'm trying to display an object from a JSON string on a website (probably not the right terminology but you know... I'm new...). Here's the cURL code I'm using:
$url="http://mc.gl:8081/?JSONSERVER=lobby";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
Then I have this that's supposed to do something (I really dont understand it)
// Will dump a beauty json :3
var_dump(json_decode($result));
Annnnnddd.... what do I do next? I've done a lot of googling and nothing seems to work. Here's the string that I should be getting:
{"lobby":{"playeramount":1,"players":{"MisterErwin":"MisterErwin"}},"API-Version":"1","return":true}
and I want to echo "playeramount".
Any help would be greatly appreciated! Thanks so much!
The var_dump() function in PHP is used to display structured information about variables. It is usually used for debugging and has nothing to do with the JSON decode.
In this case, the $result variable will contain the JSON string you need. To decode it, use PHP's built-in function json_decode():
$json = json_decode($result); // decode JSON string into an object
Note: It's also possible to get an associative array by passing TRUE as the second parameter to json_decode().
Once you have the object, you can traverse it to get the required value:
echo $json->lobby->playeramount;
Demo!
If you want to access the result as an associative array, you can do like this too [By passing a true flag in the json_decode() function]
<?php
$str='{"lobby":{"playeramount":1,"players":{"MisterErwin":"MisterErwin"}},"API-Version":"1","return":true}';
$str=json_decode($str,true); // Setting the true flag
echo $str['lobby']['playeramount']; //Outputs 1

Read json data from Android with php

I'm trying to read data from a decompiled application of Android with a php server. I used wireshark to understand what types of data the application sends, and the result is:
{"initType":"first time","parameters":true,"details":................}
I trying to capture this data and insert them in a file with this php code:
<?php
$json = $_POST["initType"];
$decoded = json_decode($json, TRUE);
if ($decoded === FALSE) {
throw new Exception('Bad JSON format.');
}
$file_handle = fopen('tmp.json', 'w');
fwrite($file_handle, $decoded);
fclose($file_handle);
?>
The file is correctly generated but it's empty. What is the error?
Because $decoded is an array, use a loop to write it to file or write the encoded JSON to file ($json). Try using this:
fwrite('tmp.json', print_r($decoded, TRUE));
or:
file_put_contents('tmp.json', print_r($decoded, TRUE));
Update (per your comments):
If you run a print_r($decoded) and it prints nothing, there is a problem with the decoding process of the JSON object passed in. I would recommend checking this to make sure it is formatted correctly. JSON formatting is a strict business and will halt your end goal if you are missing a double-quote or bracket. Start by echoing out $json ($_POST["initType"]) and compare the format to examples posted online (just Google "json formatting"). I can tell you that one thing that stands out to me is: "parameters":true (from your example above). I have a strong suspicion that the key true should be in double quotes. If you are positive that the JSON variable is correct syntactically, I don't think I would be of any more help. Using json_decode() to produce an array to very straight forward once you get it right.
Don't decode the json at all -this only brings the problem of trying to serialize an array that burmat mentioned in his answer.
Write to the file the json content straight away:
fwrite($file_handle, $json);
Also, though I am not PHP expert it seems you access the body of the post request wrongly. Please refer to the following post.

Categories