json_encode 返回描述字段為空
問題:
下面的PHP 代碼無法對JSON 回應中的「描述」欄位進行編碼,傳回NULL
include('db.php'); $result = mysql_query('SELECT * FROM `staff` ORDER BY `id` DESC LIMIT 2') or die(mysql_error()); $rows = array(); while($row = mysql_fetch_assoc($result)){ $rows[] = $row; } echo json_encode($rows);
數據庫架構:
CREATE TABLE `staff` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` longtext COLLATE utf8_unicode_ci, `description` longtext COLLATE utf8_unicode_ci, `icon` longtext COLLATE utf8_unicode_ci, `date` longtext COLLATE utf8_unicode_ci, `company` longtext COLLATE utf8_unicode_ci, `companyurl` longtext COLLATE utf8_unicode_ci, `appurl` longtext COLLATE utf8_unicode_ci, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
輸出:
[{"id":"4","name":"Noter 2","description":null,"icon":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","date":"1262032317","company":"dBelement, LLC","companyurl":"http:\/\/dbelement.com\/","appurl":"http:\/\/noter2.dbelement.com"},{"id":"3","name":"Noter 2","description":null,"icon":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","date":"1262032317","company":"dBelement, LLC","companyurl":"http:\/\/dbelement.com\/","appurl":"http:\/\/noter2.dbelement.com"}]
解決方案:
可能的原因是使用非UTF8 編碼檢索資料。要解決此問題,請在 SELECT 查詢之前添加以下行:
mysql_query('SET CHARACTER SET utf8');
這將確保以 UTF8 編碼檢索數據,這將允許 json_encode 正確編碼「描述」欄位。
以上是為什麼我的'json_encode”函數在 PHP JSON 回應中的描述欄位回傳 NULL?的詳細內容。更多資訊請關注PHP中文網其他相關文章!