【问题标题】:PHP MySQL JSON: Error is: Token 'start of object' not expected after outer-most array or objectPHP MySQL JSON:错误是:在最外层数组或对象之后不需要令牌“对象开始”
【发布时间】:2014-03-11 14:01:08
【问题描述】:

我创建了一个 php,它在 MySQL 数据库上执行 Select * 以返回 iOS 应用程序中使用的数据。我无法正确解析 JSON,并且收到错误消息:“在最外层数组或对象之后不需要令牌'对象的开始'”以及错误:“结束时的垃圾”。我是 PHP 的初学者,想知道是否有人可以提供一些见解?谢谢!

 <?php
 error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);

 $dbhost = "xxxxxxxxxx.xxxxxx.com";

 $dbuser = "xxxxxxx";
 $dbpass = "xxxxxx";
 //database name
 $dbdb = "xxxxx";

 //connect to mySQL
 $connect = mysql_connect($dbhost, $dbuser, $dbpass)
 or die ("connection error");

 //select database
 mysql_select_db($dbdb) or die ("database selection error"); // line 20

 //query the table android meal
 $query = mysql_query ("SELECT * FROM ScheduleDayOne");

 //create a while loop that places the returned data into an array
 while ($list = mysql_fetch_assoc($query)){

 //store the returned data into a variable
 $output = $list;

 //encode the returned data in JSON format
 echo json_encode($output);

 }
 //close connection
 mysql_close();

 ?>

如果我要放入浏览器,这里是 json 输出:

 {"id":"a1","session":"General","name":"Exhibitor Setup Begins","startTime":"0900","details":"9am Exhibitor Hall","png":"image","speaker1":"Johnson","speaker2":"Nelson","speaker3":"Kenner"}{"id":"b1","session":"General","name":"Conference Registration","startTime":"1000","details":"10am Noon Upper Level Lobby","png":"image","speaker1":"Jackson","speaker2":"Ward","speaker3":"Smith"}

【问题讨论】:

    标签: php mysql json


    【解决方案1】:

    您在没有适当分隔的情况下回显多个对象:

    ... son","speaker3":"Kenner"}{"id":"b1","session":"Ge ...
    ----------------------------^
    

    您可以将它们包装成一个数组:

    [{... son","speaker3":"Kenner"}, {"id":"b1","session":"Ge ...}]
    ^------------------------------^------------------------------^
    

    编辑:

    要在 PHP 中实现这一点,您可以这样做:

    ...
    $output = array();
    
    while ($list = mysql_fetch_assoc($query)){
        $output[] = $list;
    }
    
    echo json_encode($output);
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多