json_encode returning null on array - php

I'm trying to json_encode a php array however the "choices" part is returning null.
Array ( [indexer] => 7 [section] => 1 [question] => What does the last paragraph indicate about an optimistic perspective? [answer] => a [choices] => There has never been a culture or religion that is genuinely optimistic`It is “a riddle of the universe”`No enlightened culture sees the world in a truly optimistic manner`Optimistic perspectives are only held by the weak )
{"indexer":"7","section":"1","question":"What does the last paragraph indicate about an optimistic perspective?","answer":"a","choices":null}
any ideas why?
Edit: full code:
$check = mysqli_query($con, "select * from questions where section = '$section' and indexer = '$question'");
$result = mysqli_fetch_array($check, MYSQLI_ASSOC);
print_r($result);
echo json_encode($result);

json_encode expects all content that you're encoding to be valid UTF-8. If any part of the content isn't proper UTF-8, json_encode will fail silently for that part (b
All string data must be UTF-8 encoded.
My guess is that the “ marks isn't properly UTF-8 encoded (but originates from a CP1252 based encoding).
See json_last_error to retrieve the last error code from the json module.

Related

PHP json_encode isnt converting the array to JSON [duplicate]

I have the following array:
Array
(
[BookDateID] => 4
[HotelName] => Adams’ Inn
)
Output:
{"BookDateID":"4","HotelName":null}
Any magic?
BTW, I have an alternative solution by looping thru each array and have them mb_convert_encoding(str,'HTML-ENTITIES') but I want the character remains the same as I have to insert this into a DB.
foreach($array as $key=>$value){
$array[$key] = mb_convert_encoding($value,'HTML-ENTITIES');
}
json_encode needs UTF-8 encoded data. Make sure the data is UTF-8 encoded; currently it's likely Latin-1 encoded. How to do this depends on where the data comes from. Read What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text and Handling Unicode Front To Back In A Web App.

Æøå in returned JSON result - the data doesn't look like it's supposed to

I have fetched some data from a url request using JSON with the following code:
$url = 'https://recruit.zoho.com/ats/private/xml/JobOpenings/getRecords?authtoken=$at&scope=recruitapi';
$request = new WP_Http;
$result = $request->request($url, $data = array());
$input = json_encode($result, true);
var_dump($input);
This code worked absolutely fine, except the data coming out looked really weird, such as:
"content-encoding":"gzip","vary":"Accept-Encoding","strict-transport-security":"max-age=15768000"},"body":"\u003C?xml version=\"1.0\" encoding=\"UTF-8\" ?\u003E\n\u003Cresponse uri=\"\/ats\/private\/xml\/JobOpenings\/getRecords\"\u003E\u003Cresult\u003E\u003CJobOpenings\u003E\u003Crow no=\"1\"\u003E\u003CFL val=\"JOBOPENINGID\"\u003E\u003C![CDATA[213748000001263043]]\u003E\u003C\/FL\u003E\u003CFL val=\"Published in website\"\u003E\u003C![CDATA[false]]\u003E\u003C\/FL\u003E\u003CFL val=\"Modified by\"\u003E\u003C![CDATA
After some research, I realize that part of the problem most likely is the fact that there are æ, ø, and å in the data I'm requesting. Others have solved the problem this way:
$input = json_encode(utf8_decode($result), true);
However this gives me this error:
Warning: utf8_decode() expects parameter 1 to be string, array given in
I know the array is not a string, but how else do I deal with this? It seems to have worked for others, and I cant figure out why.
Thanks.
Edit:
I noticed this in the beginning of the printed data.
string(31486) "{"headers":{"server":"ZGS","date":"Wed, 12 Aug 2015 13:59:32 GMT","content-type":"text\/xml;charset=utf-8"
Does that mean it is already UTF-8 and I'm totally off?
What you receive in $result is an utf-8 string that seems to represent an url of some sort. Anyhow, json_encode will escape any unicode character to \u008E strings.
If you don't want to escape utf-8 character, this question is relevent to you : Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?
Everything seems to work fine from what I see. Although, the string you have provided us seem to be troncated but I guess this is an error on your part.

display data from an array in json form

i got an array from echo $posts
Array
(
[0] => Array
(
[id] => 14
[name] => اسطنبوليه
)
)
i have this array (part of the main array)and now i wish to convert it to json form. however i am not able to do so, i tried to convert the data through
echo json_encode ($posts);
but instead of original data i am getting an output u0627u0633u0637u0646u0628u0648u0644u064au0647n
can anyone tell how i can get the correct form
Please try echo json_encode($posts,JSON_UNESCAPED_UNICODE) (php 5.4 and above)
2 things. Firstly view source of the output in the browser and you should see it as a JSON encoded string rather than the interpreted version.
Secondly it looks like there is some character encoding issues as the string you're getting back is unicode. Make sure you have the encoding set right on your server and browser.

Character Loss converting _GET Array to URL string

Having a very bizarre issue with the conversion of a $_GET request into a string.
(PHP 5.2.17)
Here is a small snippet of the problem area of the array from print_r():
_GET (array)
...
[address_country_code] => GB
[address_name] => Super Mario
[notify_version] => 3.7
...
There are two cases the _GET data is used:
Case 1): Saved then used later:
// Script1.php
$data = json_encode($_GET);
# > Save to MySQL Database ($data)
// Script2.php (For Viewing & Testing URL later)
# > Load from Database ($result)
echo http_build_query(json_decoded($result,true));
Result of above array snippet: (CORRECT OUTPUT)
address_country_code=GB&address_name=Super+Mario&notify_version=3.7
Case 2): Used in same script as Case 1) just before its saved in Case 1):
// Script1.php
echo http_build_query($_GET);
Results in: (INCORRECT OUTPUT)
address_country_code=GB&address_name=Super+Mario¬ify_version=3.7
How is it possible that a few chars are output as a ¬ in case 2 yet case 1 is fine!
It is driving me insane :(
I have tried also instead of using http_build_query a custom function that generates the url using urlencode() in the Key and Value of the foreach loop, this just resulted in the the ¬ being changed to %C2%AC in one of my test cases!
Everything is ok with your data. You can verify it if you do:
$query = http_build_query($_GET);
parse_str($query, $data);
print_r($data);
you will get the correct uncorrupted data.
And the reason why you see ¬ symbol is how browser interprets html entities. ¬ is represented as ¬ But browser will render it even without semicolon at the end.
You're most likely displaying this data in a web browser and that is interpreting
&not
as special HTML entity.
Pls see this: https://code.google.com/p/doctype-mirror/wiki/NotCharacterEntity
Try doing
var_dump(http_build_query($_GET))
instead of:
echo http_build_query($_GET)
and see HTML source to get/verify actual string.
So, even though both cases output to web a web browser and both convert from an array using http_build_query().
I fixed problem in Case 2 by replacing http_build_query (Case 1 still uses it..) with this function:
htmlspecialchars(http_build_query($_GET));

json_encode problem

This has got me completely stumped:
print_r($json);
echo json_encode($json);
output:
Array
(
[query] => dia
[suggestions] => Array
(
[0] => Diana Johnson
[1] => Diane Abbott
)
)
{"query":"dia","suggestions":[null,null]}
What on earth is going wrong?
edit Just to add to the general wtf-ery of this, here's another sample:
Array
(
[query] => david
[suggestions] => Array
(
[0] => David Cameron
[1] => David Amess
[2] => David Anderson
[3] => David Blunkett
[4] => David Burrowes
)
)
{"query":"david","suggestions":["David Cameron",null,null,null,null]}
I'm posting this as an answer because I need the full formatting abilities of the normal answer box.
Yeah, it's UTF-8 all right. From the PHP interactive prompt:
php > $david = urldecode('David%A0Amess');
php > echo json_encode($david);
null
php > $david = urldecode('David%20Amess');
php > echo json_encode($david);
"David Amess"
php > $david = urldecode('David%c2%a0Amess');
php > echo json_encode($david);
"David\u00a0Amess"
So, we can assume that you're dealing with either ISO-8859 or Windows-1252, given that we're dealing with a broken NBSP. We can fix this with iconv:
php > $david = urldecode('David%A0Amess');
php > $david_converted = iconv('Windows-1252', 'UTF-8', $david);
php > echo json_encode($david_converted);
"David\u00a0Amess"
So, this means that you are going to need to not trust what you're pulling out of MySQL, assuming you've done the SET NAMES thing. Clearly something has gone awry when you were inserting data. You probably weren't giving MySQL well-formed UTF-8, and it stupidly did not complain. (If you were using other, smarter, more correct databases, and tried to insert the unencoded NBSP, they would have rejected the input.)
This looks like an autocomplete script. I assume your results are loaded from a database, are you sure they're utf-8? If you cannot replicate this functionality by hardcoding the array, then it's probably an encoding issue.
According to http://php.net/manual/en/function.json-encode.php, "This function only works with UTF-8 encoded data."
You can also use http://php.net/manual/en/function.json-last-error.php to see the last error.

Categories