PHP json编码的JSON格式无效

时间:2013-10-08 22:00:47

标签: javascript php mysql json jsonp

我有一个编码Json数据的PHP文件,当我在单个数据块中查看JSON输出时,我得到一个有效的json代码语法,这是一个例子: single data block

但是当JSON导致多个数据块时,它会生成一个无效的JSON格式,如下所示:multiple data blocks

这是我的PHP代码:

<?php 
header('Content-Type: application/json; charset=utf-8', true,200);
DEFINE('DATABASE_USER', 'xxxxx');
DEFINE('DATABASE_PASSWORD', 'xxxxxx');
DEFINE('DATABASE_HOST', 'xxxxxxxxxxx');
DEFINE('DATABASE_NAME', 'xxxxxxxx');

// Make the connection:
$dbc = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
 DATABASE_NAME);
$dbc->set_charset("utf8");
if (!$dbc) {
 trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}


if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra  space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation

$query = "select name,franco,alpha,id,url,songkey,chord from song where name like '%$keyword%' or franco like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .

$result = mysqli_query($dbc,$query);//Run the Query

if($result){//If query successfull
 if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
 while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record

 $data = array();
 $data = $row;  
 echo $_GET[$callback]. ''.json_encode($data).'';
 }
 }else {
 echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
 }

}
}else {
 echo 'Parameter Missing in the URL';//If URL is invalid
}
?>

1 个答案:

答案 0 :(得分:2)

这是因为您在时间上对结果集的单行进行JSON编码。如果调用客户端期望这样,那么这不是有效的JSON结构。

可能,您需要将每一行作为数组中的条目,然后JSON编码并回显生成的数组。

像这样:

if($result){//If query successfull
    if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
        $array = array();
        while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
            $array[] = $row;
        }
        echo json_encode($array);
    }
}