使用 PHP 回发 json 值时出现意外错误


Unexpected error when posting back json value using PHP

我正在使用Ajax将一些数据从我的服务器端代码PHP回发到我的客户端,这就是它是如何完成的

//server side
$json="{
"payout_history":"0",
"round_shares":"1816",
"workers":
   {
    "jbo.5970":
      {
        "alive":"1",
        "hashrate":"1253"
      },
    "jbo.5970cpu":
      {
        "alive":"1",
        "hashrate":"21"
      },
    "jbo.5970-2":
      {
        "alive":"1",
        "hashrate":"1062"
      }
  }
}";
echo json_encode($json);

我在Firebug的响应页面中收到此错误,我无法弄清楚它出了什么问题

    <br />
<b>Parse error</b>:  syntax error, unexpected 'payout_history' (T_STRING) in         
<b>C:'xampp'htdocs'exercise5json'display.php</b> on line <b>38</b><br />

您没有正确嵌套引号。您需要将 JSON 字符串括在单引号中,而不是双引号中:

$json = '{"myTag":"myData"}';

或者更好的是 - 将数组创建为 PHP 数组并使用 json_encode() 为您生成 JSON。

更简单的

方法是将数据设为array并将其传递给json_encode(),例如:

$json = array(
    "payout_history" => 0,
    "round_shares"  => 1816
    ....
);
echo json_encode($json);

代码中的问题存在于使用引号设置$json字符串的方式上。

看看关于使用引号的 PHP 文档:http://php.net/manual/en/language.types.string.php

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I''ll be back"';

但是,正如@Sudhir之前所说,最好有一个数组并正确使用 json_encode 函数输出 JSON。

$json = array(
    "payout_history" => 0,
    "round_shares"  => 1816
    // ....
);
header("Content-Type: application/json");
echo json_encode($json);