2014-04-25 30 views
0

我從mysqli的數據庫使用jquery職位和一個PHP文件中檢索數據之間的空格。我的一個數據庫字段是中等文本。我正在以json的形式檢索數據。當我把JSON數據轉換成JSON皮棉,我得到:JSON絨毛去除的話

Parse error on line 92: 
...e said to himself, "Iwanttoknowmoreabout 
-----------------------^ 
Expecting '}', ':', ',', ']' 

...我注意到,JSON皮棉已經去掉了一些單詞之間的空格。這是我的PHP代碼:

require_once ('constants.php'); 
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 
if (mysqli_connect_errno()) { 
    printf("Connect failed: %s", mysqli_connect_error()); 
    exit; 
} 
$qNations = "SELECT b.Country, a.CountryCode, a.population, a.GDP, a.Income_level, b.Name, b.Age, b.Occupation, b.Origin, b.Neighborhood, b.FromHome, b.Video, b.PersonImage, b.CountryImage, b.WorldImage, b.Image2, b.Image3, b.Image4, b.Image5, b.Image6, b.Notes FROM countries a, people b where a.CountryID = b.CountryID order by a.Country"; 
$result = $db->query($qNations); 

$numrecords = mysqli_num_rows($result); 
$count = 0; 
$strResults = '{"people": ['; 
while ($row = $result->fetch_array(MYSQLI_ASSOC)) { 
    $count++; 
    $story = $row['Notes']; 

    $strResults .= '{ 
         "country":"' . $row['Country'] . '", 
         "countryCode":"' . $row['CountryCode'] . '", 
         "population":"' . $row['population'] . '", 
         "GDP":"' . $row['GDP'] . '", 
         "income_level":"' . $row['Income_level'] . '", 
         "name":"' . $row['Name'] . '", 
         "age":"' . $row['Age'] . '", 
         "occupation":"' . $row['Occupation'] . '", 
         "origin":"' . $row['Origin'] . '", 
         "neighborhood":"' . $row['Neighborhood'] . '", 
         "story":"' . $story . '" 
        }'; 
    if ($count < $numrecords) { //only add a comma if there are more records to go 
     $strResults .= ','; 
    } 
} 
$strResults .= ']}'; 

$db->close(); 
echo $strResults; 

什麼是格式和/或JSON返回媒體文本數據庫字段的最佳方法?

+0

不要手動編碼您的JSON,傾倒在數組中的一切,用'回聲json_encode($ your_array);'在盡頭你的腳本。並確保沒有其他輸出產生。的 – jeroen

+0

可能重複的[如何:正確使用PHP數據編碼爲JSON格式,並與jquery請求數據AJAX /(http://stackoverflow.com/questions/21491910/how-to-properly-use-php-到編碼數據 - 到 - JSON格式和 - 請求的數據-W) – jeroen

回答

4

你不知道。你永遠不應該自己構建JSON。爲您打造一個NATIVE PHP數據結構,然後用json_encode()它爲你翻譯。

這意味着,而不是建立一個JSON字符串,你建立一個PHP數組來代替:

$data = array(); 
while($row = $result->fetch_array(MYSQLI_ASSOC)) { 
    $data[] = $row; 
} 
echo json_encode($data); 

記住,JSON基本上是JavaScript代碼。你必須建立語法有效的JavaScript,這意味着逃避任何內部引號:

var name = 'Miles O'Brien'; /// what you're building - an unterminated string 
var name = 'Miles O\'Brien'; // what you SHOULD have built. 
+0

或簡單地在1行'回波json_encode($ result-> fetch_all(MYSQLI_ASSOC));' – DanFromGermany

+0

@Marc B:如何你逃避內部報價? – LauraNMS

+0

你沒有。 json_encode()爲你處理所有這些。 PHP數據進來了,json出來了。它將是有效的json。 –