【发布时间】:2019-01-19 20:41:31
【问题描述】:
我有这个 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 文件时,我收到此错误消息:
语法错误:JSON.parse:第 1 行第 1 列的意外字符 JSON 数据
为什么会这样?
附:当然,当我评论这一行时://header("Content-type: application/json"); 错误信息消失了
编辑:遵循以下 cmets 的新代码版本:
<?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;
?>
仍然收到相同的错误消息
【问题讨论】:
-
你真的回显了 json 吗?
-
那么在
header()行之后你尝试了echo $json;并且你得到一个错误? -
你试过
ehco而不是echo^ -
哦...是的,对不起,...现在它输出正确,但错误仍然存在
-
将
echo放在header()行之后。