对象中的特殊字符导致 json_encode 抛出错误
向知识的守护者致敬,希望这个愚蠢的问题能够让您身体健康,
我已经开始学习 PHP,并且作为这一光荣事业的一部分,我正在尝试为 MySql DB 创建一个 RESTful API。我在 PHP 5.3 之上使用 Slim。到目前为止,一切都很好。但我也住在丹麦,这显然是一个问题,因为我们喜欢使用“æ”、“ø”和“å”等字符。
因此,当我向我奇妙的 RESTful 装置询问一个没有奇怪字符的对象时,它礼貌地回答:
{
id: "3",
name: "Wall - Plaster",
price: "200",
unit: "m2",
tags: "1"
}
但是,唉。当要求返回带有“æ”或任何其他奇怪字符的对象时,事情不会那么顺利:
FOOL! json_encode(): Invalid UTF-8 sequence in argument
utf8_encode() 和 Iconv.conv() 适用于字符串和数组。但我可以用什么来表示对象呢?有什么方法可以迭代一个对象,比如 foreach 吗?
我的数据库和表都是UTF8格式的。
我的排外功能受到质疑:
function getItem($id) {
$sql = "SELECT * FROM items WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$item = $stmt->fetchObject();
$db = null;
echo json_encode($item);
//echo $item;
//print_r($item);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
谢谢你,愿处女们带着发酵大麦的礼物涌向你。
All hail the keepers of knowledge and may this stupid question reach you in good health,
I've set forth to learn PHP, and as part of that glorious venture, I'm trying to create a RESTful API to a MySql DB. I'm using Slim on top of PHP 5.3. So far, so good. But I also live in Denmark, which is a problem (apparantly) because we like to use chars like 'æ', 'ø' and 'å'.
So, when I ask my fantastic RESTful contraption for an object without strange chars, it politely replies:
{
id: "3",
name: "Wall - Plaster",
price: "200",
unit: "m2",
tags: "1"
}
But, alas. Things do not go so well when it is asked to return an object with an 'æ' or any other strange char:
FOOL! json_encode(): Invalid UTF-8 sequence in argument
utf8_encode() and Iconv.conv() works for strings and arrays. But what can I use for an object? Is there some way I could iterate my way through an object, like foreach?
My DB and table are both in UTF8.
My xenophobic function in question:
function getItem($id) {
$sql = "SELECT * FROM items WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$item = $stmt->fetchObject();
$db = null;
echo json_encode($item);
//echo $item;
//print_r($item);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Thank you, and may virgins flock to you carrying gifts of fermented barley.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的数据库连接可能是 ISO-8859-1 - 它是 mySQL 连接的默认编码。因此,即使数据库是 UTF-8,您也会获得 ISO-8859-1 字符数据。
请参阅这个问题< /a> 用于更改 PDO 连接字符集的各种(永久和每个连接)方法。
Your database connection is probably ISO-8859-1 - it's the default encoding for mySQL connections. Hence, you are getting ISO-8859-1 character data even though the database is UTF-8.
See this question for various (permanent and per-connection) ways to change PDO's connection character set.