playeren
playeren

Reputation: 87

Special characters in object causes json_encode to throw error

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.

Upvotes: 0

Views: 2841

Answers (1)

Pekka
Pekka

Reputation: 449843

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.

Upvotes: 2

Related Questions