简体   繁体   中英

how to create a costume layout for json data returned from mysql database for UTF-8 characters in php

I am trying to create a json representation of mysql data in a restful webservice using php. my returned json should look something like this:

"worktypes" :
[
    {
        "id" : "1",
        "name" : "نوع 1",
        "isactive" : "true"
    },
    {
        "id" : "2",
        "name" : "نوع 2",
        "isactive" : "false"
    }
]

one of my options was to iterate through my result records and echo each line by hand. It was working until I reached utf8 characters shown above (like 'نوع 1') and instead of ending up with something like \Ù\†\Ù\ˆ\Ø\¹ I got unreadable symbols like ÃÂÃÂù çÃÂà.

If I could use json_encode somehow to create this layout, it would automatically solve this problem;But I don't know how to create such a structure in php that its json_encoded string represents my desired layout.

My other option is to somehow encode these characters myself. But I don't know how to do that either.

Could anyone help me with my problem?

UPDATE: I use a simple echo in my webservice when I get unusual characters like :

$result = array("1" => "نوع 1")
echo $result;

//results in 'ÙÙع 1' when called using webservice

The equivalent PHP array to what you have given is:

$x = array(
    "worktypes" => array( 
        array(
            "id" => "1",
            "name" => "نوع 1",
            "isactive" => "true"
        ),
        array(
            "id" => "2",
            "name" => "نوع 2",
            "isactive" => "false"
        )
    )
);

You can then use json_encode .

Note that you may still see escaped characters, but the browser should be able to handle unescaping them when it parses the JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM