我使用jquery post和php文件从mysqli数据库中检索数据。我的一个数据库字段是中等文本。我以json的形式检索数据。当我将json数据放入json lint时,我得到:
Parse error on line 92:
...e said to himself, "Iwanttoknowmoreabout
-----------------------^
Expecting '}', ':', ',', ']'
...我注意到json lint删除了一些单词之间的空格。这是我的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 :(得分: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.