简体   繁体   English

php JSON_encode不能正常工作

[英]php JSON_encode not working

I want to get this JSON output from this . 我想从这里得到这个 JSON输出。 unfortunately json_encode() function won't encode array into that format. 遗憾的是,json_encode()函数不会将数组编码为该格式。 It's nothing returning at all. 根本没有任何回报。 here is my code.` 这是我的代码

$output = array(
    'responseData' => array(),
    'responseDetails' => null,
    'responseStatus' => 200
);

$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
    foreach ($row as $k => $v) {
        $output['responseData']['result'][$x][$k] = $v;
    }
    $x++;
}

print_r($output);
header('Content-Type: application/json');
echo json_encode($output , JSON_FORCE_OBJECT);

I can't find the reason. 我找不到原因。 someone please help me find the solution. 有人请帮我找到解决方案。

Edit : Sorry. 编辑:对不起。 Here is outputs - 这是输出 -

Expected JSON output - 预期的JSON输出 -

{
"responseData": {
    "results": [{
        "qid": 1,
        "qtitle": "When do we finish this project ?",
        "qimage_url": "http://www.wearesliit.com/example.png",
        "user": "samith",
        "date": "2016-01-01T02:15:12.356Z",
        "type": 1,
        "category": 5,
        "tags": ["common_senese", "truth", "bazsa_awsanna"],
        "note": "Sample quetion"
    }, {}, {}]
},
"responseDetails": null,
"responseStatus": 200 }

I don't get any JSON output at all. 我根本没有得到任何JSON输出。 but here is the print_r result of the array. 但这是数组的print_r结果。

 Array(
[responseData] => Array
    (
        [result] => Array
            (
                [0] => Array
                    (
                        [question_ID] => 1
                        [question_Title] => Which shape does not belong with the other three shapes?
                        [question_Image_URL] => http://www.wearesliit.com/images/quiz/questions/1.jpg
                        [quetion_Note] => Easy IQ question.
                        [category_ID] => 7
                        [username] => samith
                        [added] => 2017-01-29 21:50:52
                    )

                [1] => Array
                    (
                        [question_ID] => 2
                        [question_Title] => Tim earns $10 per hour at his job.  When he gets paid on Friday, he is paid for 40 hours of work.  He then goes out and spends 10% of his earnings on entertainment that weekend.  How much money is he left with on Monday?
                        [question_Image_URL] => 
                        [quetion_Note] => Easy IQ question.
                        [category_ID] => 7
                        [username] => samith
                        [added] => 2017-01-29 21:50:52
                    )
            )

    )

[responseDetails] => 
[responseStatus] => 200 )

Thanks to @awiebe I found the exact error. 感谢@awiebe,我发现了确切的错误。 It's 它的

Malformed UTF-8 characters, possibly incorrectly encoded 格式错误的UTF-8字符,可能编码错误

Thank you all, I found a solution from an another question. 谢谢大家,我找到了另一个问题的解决方案。 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel 在Laravel中,'格式错误的UTF-8字符,可能是错误编码的'

json_encode() function returns "false" when the encode fails and a "false" result does not appear in an echo or print. 当编码失败并且回显或打印中没有出现“假”结果时,json_encode()函数返回“false”。 See: http://php.net/manual/en/function.json-encode.php The best way to handle such problems would be using the json_last_error_msg() method and performing an action according to the found error. 请参阅: http ://php.net/manual/en/function.json-encode.php处理此类问题的最佳方法是使用json_last_error_msg()方法并根据发现的错误执行操作。 See: http://php.net/manual/en/function.json-last-error-msg.php . 请参阅: http//php.net/manual/en/function.json-last-error-msg.php An example would be: 一个例子是:

$show_json = json_encode($output , JSON_FORCE_OBJECT);
if ( json_last_error_msg()=="Malformed UTF-8 characters, possibly incorrectly encoded" ) {
    $show_json = json_encode($API_array, JSON_PARTIAL_OUTPUT_ON_ERROR );
}
if ( $show_json !== false ) {
    echo($show_json);
} else {
    die("json_encode fail: " . json_last_error_msg());
}

The thing is, if the problem was an encoding character, it will no be shown. 问题是,如果问题是编码字符,则不会显示。 Just hope that character is not essential for your work or if you can find the mismatch input in a zigazillion string list, correct it. 只是希望角色对你的工作不是必不可少的,或者如果你能在zigazillion字符串列表中找到不匹配输入,那就纠正它吧。 Other types of errors can be found here: http://php.net/manual/en/json.constants.php . 其他类型的错误可以在这里找到: http//php.net/manual/en/json.constants.php Just apply the if statement and correction for the error you find. 只需对您找到的错误应用if语句和更正。

I hope this helps someone. 我希望这可以帮助别人。

remove 去掉

header('Content-Type: application/json');

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. 请记住,在发送任何实际输出之前,必须通过普通HTML标记,文件中的空行或PHP来调用header()。 It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. 使用include或require,函数或其他文件访问函数读取代码是一个非常常见的错误,并且在调用header()之前输出空格或空行。 The same problem exists when using a single PHP/HTML file. 使用单个PHP / HTML文件时存在同样的问题。

and JSON_FORCE_OBJECT from JSON_FORCE_OBJECT来自

echo json_encode($output , JSON_FORCE_OBJECT);

I would like to refer you about this issue, on link I suggest you use a json_encode wrapper like this : 我想就此问题向您推荐,在链接上我建议您使用这样的json_encode包装:

function safe_json_encode($value){
if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
    $encoded = json_encode($value, JSON_PRETTY_PRINT);
} else {
    $encoded = json_encode($value);
}
switch (json_last_error()) {
    case JSON_ERROR_NONE:
        return $encoded;
    case JSON_ERROR_DEPTH:
        return 'Maximum stack depth exceeded'; // or trigger_error() or throw new Exception()
    case JSON_ERROR_STATE_MISMATCH:
        return 'Underflow or the modes mismatch'; // or trigger_error() or throw new Exception()
    case JSON_ERROR_CTRL_CHAR:
        return 'Unexpected control character found';
    case JSON_ERROR_SYNTAX:
        return 'Syntax error, malformed JSON'; // or trigger_error() or throw new Exception()
    case JSON_ERROR_UTF8:
        $clean = utf8ize($value);
        return safe_json_encode($clean);
    default:
        return 'Unknown error'; // or trigger_error() or throw new 
Exception();
}
}


function utf8ize($mixed) {
if (is_array($mixed)) {
    foreach ($mixed as $key => $value) {
        $mixed[$key] = utf8ize($value);
    }
} else if (is_string ($mixed)) {
    return utf8_encode($mixed);
}
return $mixed;
}

And after define these function you can use it direct, 定义这些功能后你可以直接使用它,

echo safe_json_encode($response);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM