mysql - PHP json_encode encoding accents in words -
this question has answer here:
i'm using opencart, , althought have seen every post on google subject, can't figure out why database saving letters accents in non utf8 encoding.
print_r($this->request->post); returns: array ( [pfa_status] => 1 [pfa_text] => 'cobrança' ); after aplying json_encode becomes:
{"pfa_status":"1","pfa_text":"cobran\u00e7a"} now looking @ possible solutions through web:
- i use
<meta http-equiv="content-type" content="text/html;charset=utf-8"> - i have tried
header('content-type: text/plain; charset=utf-8'); - all files have format
utf-8 without bom - i use
$this->connection->set_charset("utf8"); - i use
$this->connection->query("set names 'utf8'"); - my field in database, saved json, has collation
utf8_bin - when using
json_decoderemains wrong encoding - tried
json_encode($this->request->post, json_unescaped_unicode);
so, whenever show value of pfa_text after being decoded, shows cobran\u00e7a instead of cobrança.
what missing?
edit 1: requested, here's code sake of testing.
class controllerpfa extends controller { public function index() { if (($this->request->server['request_method'] == 'post')) { $value = json_encode($this->request->post, json_unescaped_unicode); print_r($value); die(); } } } so output (and take notice full current $_post response):
{"pfa_status":"1","pfa_sort_order":"","pfa":[{"payment_method":"cod","description":{"1":{"name":"tax"},"3":{"name":"cobran\u00e7a"},"4":{"name":"cobran\u00e7a"}}}]} edit 2: i'm using version 7.0 of php
edit 3: solved, following function allows words inserted in database accents.
private function formatencoding($value) { return preg_replace_callback('/\\\\u(\w{4})/', function ($matc) { return html_entity_decode('&#x' . $matc[1] . ';', ent_compat, 'utf-8'); }, $value); } so, have call formatencoding(json_encode($this->request->post));
one of options can pass in second parameter of json_encode json_unescaped_unicode. described as:
encode multibyte unicode characters literally (default escape \uxxxx). available since php 5.4.0.
so if pass that, should work because prevents them being escaped:
$json = json_encode($data, json_unescaped_unicode); 
Comments
Post a Comment