2013-10-08 66 views
0

我具有編碼JSON數據,當我觀看JSON輸出時它的一個單一的數據塊i得到一個有效的JSON代碼語法,這是一個例子的PHP的文件: single data block無效JSON格式

但是,當在多數據的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 
} 
?> 

回答

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); 
    } 
} 
+0

謝謝麥克,這解決了我的problem.Thank你這麼多好友 – Bishak