我有一些数据存储在MySQL表中,我用PDO来获取这些数据。该函数将查询结果放入一个数组中,并且所有字段都存在:
Array (
[0] => Array ( [id] => 1 [nome] => Oggetto 1 [descr] => Questa è la favolosa descrizione dell'oggetto 1 [prezzo] => 50.00 [imgpath] => dummy.jpg [url] => http://localhost/ [cat] => 1 [avail] => 1 )
[1] => Array ( [id] => 2 [nome] => Oggetto 2 [descr] => Questa è la favolosa descrizione dell'oggetto 2 [prezzo] => 45.00 [imgpath] => dummy.jpg [url] => http://localhost/ [cat] => 1 [avail] => 1 )
[2] => Array ( [id] => 3 [nome] => Oggetto 3 [descr] => Questa è la meravigliosa descrizione dell'oggetto 3 [prezzo] => 120.00 [imgpath] => dummy.jpg [url] => http://localhost/ [cat] => 3 [avail] => 1 )
[3] => Array ( [id] => 4 [nome] => Oggetto 4 [descr] => Questa è la meravigliosa descrizione dell'oggetto 4 [prezzo] => 200.00 [imgpath] => dummy.jpg [url] => http://localhost [cat] => 2 [avail] => 1 )
[4] => Array ( [id] => 5 [nome] => Oggetto 5 [descr] => Questa è la fantasiosa descrizione dell'oggetto 5 [prezzo] => [imgpath] => dummy.jpg [url] => http://locahost [cat] => 4 [avail] => 1 ) )
问题是我需要一个json格式的数据响应,所以我使用json_encode
函数将PHP数组转换为json格式的数据,但从下面的输出中可以看到,字段descr
已经丢失,我不知道为什么:
[
{"id":"1","nome":"Oggetto 1","descr":null,"prezzo":"50.00","imgpath":"dummy.jpg","url":"http:'/'/localhost'/","cat":"1","avail":"1"},
{"id":"2","nome":"Oggetto 2","descr":null,"prezzo":"45.00","imgpath":"dummy.jpg","url":"http:'/'/localhost'/","cat":"1","avail":"1"},
{"id":"3","nome":"Oggetto 3","descr":null,"prezzo":"120.00","imgpath":"dummy.jpg","url":"http:'/'/localhost'/","cat":"3","avail":"1"},
{"id":"4","nome":"Oggetto 4","descr":null,"prezzo":"200.00","imgpath":"dummy.jpg","url":"http:'/'/localhost","cat":"2","avail":"1"},
{"id":"5","nome":"Oggetto 5","descr":null,"prezzo":null,"imgpath":"dummy.jpg","url":"http:'/'/locahost","cat":"4","avail":"1"}
]
这可能是因为我已经将desc
声明为表中的文本字段吗?如果是这样,我如何确保该字段中的数据在从PHP数组传递到JSON格式的数据时不会丢失?
因为[descr]字符串包含扩展字符,您可能需要使用类似PHP的htmlentities函数的东西对其进行编码。
检查您的descr
字段值,字符è
在JSON中不是可执行字符,因此在获取数组结果之前使用htmlentities($_POST[descr])
。
例如:
<?php
$a = htmlentities("Questa è la favolosa descrizione dell'oggetto 1");
$arr = array('a' => $a);
echo json_encode($arr);
?>
结果是,
{"a":"Questa è la favolosa descrizione dell'oggetto 1"}
http://codepad.org/M2P8mnR8
注意:您可以使用UTF8对那些使用MYSQL本身的chracter进行编码