php/mysql:syntaxerror:json.parse:json数据的第1行第1列出现意外字符

rqenqsqc  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(265)

我有一张mysql表:

mysql> select * from  members;
+-------+-----------+-----------+
| memid | firstname | lastname  |
+-------+-----------+-----------+
|     1 | billal    | begueradj |
|     2 | bill      | gates     |
|     3 | steve     | jobs      |
+-------+-----------+-----------+
3 rows in set (0.00 sec)

我有这个密码:

<?php
$output = array('error' => false);
$members = array();

try {
    $db = new PDO('mysql:host=localhost;dbname=bill;charset=utf8',
                   'root',
                   ''
    );
} catch(Exception $e) {
    die('Error in connecting to DB: <br/>'.$e->getMessage());
}

$response = $db->query('SELECT * FROM members');
while($row = $response->fetch()){
    echo $row['firstname'].' ';
    echo $row['lastname'].'<br/>';
    array_push($members, $row);
}

$output['members'] = $members;
$response->closeCursor();
$json = json_encode($out);
echo $json; // outputs correctly
header("Content-type: application/json");    // error here
die();
?>

当我运行包含上面php代码的php文件时,我收到了这个错误消息:
syntaxerror:json.parse:json数据的第1行第1列出现意外字符
为什么会这样?
p、 当然,当我评论这句话时: //header("Content-type: application/json"); 错误信息消失
编辑:新代码版本如下:

<?php
    header("Content-type: application/json");
    $output = array('error' => false);
    $members = array();

    try {
        $db = new PDO('mysql:host=localhost;dbname=bill;charset=utf8',
                       'root',
                       ''
        );
    } catch(Exception $e) {
        die('Error in connecting to DB: <br/>'.$e->getMessage());
    }

    $response = $db->query('SELECT * FROM members');
    while($row = $response->fetch()){       
        array_push($members, $row);
    }

    $output['members'] = $members;
    $response->closeCursor();
    $json = json_encode($out); 
    //echo $json;    

?>

仍然收到相同的错误消息

z9smfwbn

z9smfwbn1#

试试这个也许能帮你

if ($response->num_rows > 0) {
        while($row[] = $response -> fetch_assoc()) {
            $item = $row;
            $json = json_encode($item);
        }
    }
bbuxkriu

bbuxkriu2#

header() 应该放在所有输出之上,所以在你回显任何东西之前。
另外,由于您没有将整个内容编码为json,而只是部分内容,我猜您缺少json的开头和结尾。
正确的json输出:
例1:

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

例2:

[
  {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  },
  {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  },
  {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  }
]

PHP:

<?php

$output = ["error" => false, "members" => []];

try {
  $db = new PDO("mysql:host=localhost;dbname=bill;charset=utf8", "root", "");
} catch(Exception $e) {
  die("Error in connecting to DB: <br/>{$e->getMessage()}");
}

$response = $db->query("SELECT * FROM members");

while($row = $response->fetch(PDO::FETCH_ASSOC)) {
  array_push($output["members"], $row);
}

$response->closeCursor();

$json = json_encode($output);

header("Content-type: application/json");

echo $json;

相关问题