我有一张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;
?>
仍然收到相同的错误消息
2条答案
按热度按时间z9smfwbn1#
试试这个也许能帮你
bbuxkriu2#
header()
应该放在所有输出之上,所以在你回显任何东西之前。另外,由于您没有将整个内容编码为json,而只是部分内容,我猜您缺少json的开头和结尾。
正确的json输出:
例1:
例2:
PHP: