0

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
playeren
  • 87
  • 1
  • 6

1 Answers1

2

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.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 2
    You, Sir, are a scholar, and most certainly a gentleman of great format! I added PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' to my connection options and now 'æ','ø' and 'å' are no longer treated as second-rate citizens. My deepest gratitude. – playeren Feb 14 '12 at 18:19
  • This resolved my problem as well (and saved SO from my creating a duplicate question). Thank you very much! – acedanger May 17 '13 at 14:01