PHP/MySQL : SyntaxError: JSON. 解析:JSON 数据第 1 行第 1 列出现意外字符

标签 php mysql json pdo

我有这个 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: unexpected character at line 1 column 1 of the JSON data

为什么会这样?

附言当然,当我评论这一行时://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;    

?>

仍然收到相同的错误消息

最佳答案

header() 应该放在所有输出之上,所以在回显任何内容之前。

另外,由于您没有将整个内容编码为 JSON,而是仅将部分内容编码为 JSON,我猜您缺少 JSON 的开头和结尾。

正确的 JSON 输出:

ex1:

{
  "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;

关于PHP/MySQL : SyntaxError: JSON. 解析:JSON 数据第 1 行第 1 列出现意外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51816879/

相关文章:

php - 处理访问日志的算法

php - 我应该在哪里使用 isset() 和 !empty()

php - Wordpress Woocommerce 从自定义运输字段 (AJAX) 中获取值(value)

mysql - 外键引用复合主键

php - 用户 'www-data' 的访问被拒绝 @'localhost'

sql - JSON_VALUE() 在 SQL Azure v12 中停止工作?

php - 无脂 sample 示例失败

PHP 受影响的行 = 1 无法正常工作

javascript - 执行插入 .innerHTML 的 src 脚本

c# - 使用 JSON 的有效方法