【问题标题】:php JSON_encode not workingphp JSON_encode 不工作
【发布时间】:2017-06-17 17:53:56
【问题描述】:

我想从 this 获取 this JSON 输出。不幸的是 json_encode() 函数不会将数组编码为该格式。根本就什么都没有回来。这是我的代码。`

$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);

我找不到原因。有人请帮我找到解决方案。

编辑:对不起。这是输出 -

预期的 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 }

我根本没有得到任何 JSON 输出。但这里是数组的 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 )

【问题讨论】:

  • 什么 JSON 输出来自什么?介意将其包含在您的问题中吗?
  • @Anant 第二个链接,我猜。
  • 因为它在你的代码中显示print_r($output);的结果。
  • 删除print_r,使用echo json_encode($output)
  • int json_last_error ( void )

标签: javascript php json api


【解决方案1】:

感谢@awiebe,我找到了确切的错误。这是

格式错误的 UTF-8 字符,可能编码不正确

谢谢大家,我从另一个问题中找到了解决方案。 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

【讨论】:

  • ? 你救了我。
【解决方案2】:

json_encode() 函数在编码失败并且回显或打印中没有出现“假”结果时返回“假”。见:http://php.net/manual/en/function.json-encode.php 处理此类问题的最佳方法是使用 json_last_error_msg() 方法并根据发现的错误执行操作。请参阅:http://php.net/manual/en/function.json-last-error-msg.php。 一个例子是:

$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());
}

问题是,如果问题是编码字符,它将不会显示。只是希望该字符对您的工作不是必需的,或者如果您可以在一个千变万化的字符串列表中找到不匹配的输入,请更正它。可以在此处找到其他类型的错误:http://php.net/manual/en/json.constants.php。只需对您发现的错误应用 if 语句和更正即可。

我希望这对某人有所帮助。

【讨论】:

    【解决方案3】:

    我想向您介绍这个问题, 在link 我建议你使用这样的 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;
    }
    

    定义好这些函数后就可以直接使用了,

    echo safe_json_encode($response);
    

    【讨论】:

      【解决方案4】:

      删除

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

      请记住,header() 必须在发送任何实际输出之前调用,无论是通过普通 HTML 标记、文件中的空白行还是通过 PHP。使用 include 或 require 函数或其他文件访问函数读取代码并在调用 header() 之前输出空格或空行是一个非常常见的错误。使用单个 PHP/HTML 文件时也存在同样的问题。

      JSON_FORCE_OBJECT来自

      echo json_encode($output , JSON_FORCE_OBJECT);
      

      【讨论】:

      • 好吧,如果您需要返回的数据是 application/json,那么删除这个 header 指令是一个合适的答案吗?
      猜你喜欢
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 2015-01-19
      • 2011-09-04
      相关资源
      最近更新 更多