【发布时间】:2012-06-01 08:02:27
【问题描述】:
我有一个要在 json 中编码的数据库结果,以前我在将数据导入数据库时遇到编码问题(phpmyadmin 上的奇怪字符),但现在我在插入数据之前通过 utf8_decode() 修复了它。
所以现在我检索我的数据,但字符串有问题...
echo '<pre>';
var_dump($product);
echo '<br>';
var_dump( json_encode($product));
echo '</pre>';
echo '<br>'.mb_detect_encoding($product->name);
echo '<br>'.$product->name;
echo '<br>'.mb_convert_encoding($product->name, 'ISO-8859-1');
$product->name = 'H2O AUDIO Waterproof-Ohrhörer Surge Pro Mini BA1-GY';
echo '<br>Revu encode: '.mb_detect_encoding($product->name);
echo '<br>'.mb_detect_encoding($product->name);
echo '<br>Revu: '.$product->name;
echo '<br>'.mb_convert_encoding($product->name, 'ISO-8859-1');
echo '<br>';
var_dump( json_encode($product));
这给了我:
object(Application_Model_Product)#42 (13) {
["id_product"]=>
string(6) "359805"
["id_community_ask"]=>
NULL
["barcode"]=>
string(13) "3000000010907"
["name"]=>
string(51) "H2O AUDIO Waterproof-Ohrhörer Surge Pro Mini BA1-GY"
["description"]=>
NULL
["image"]=>
NULL
["status"]=>
string(1) "2"
["nb_votes_halal"]=>
string(1) "0"
["nb_votes_harram"]=>
string(1) "0"
["date_created:protected"]=>
NULL
["date_edited:protected"]=>
NULL
["updated:protected"]=>
string(1) "0"
["imported:protected"]=>
string(1) "1"
}
string(173) "{"id_product":"359805","id_community_ask":null,"barcode":"3000000010907","name":null,"description":null,"image":null,"status":"2","nb_votes_halal":"0","nb_votes_harram":"0"}"
UTF-8
H2O AUDIO Waterproof-Ohrhörer Surge Pro Mini BA1-GY
H2O AUDIO Waterproof-Ohrhörer Surge Pro Mini BA1-GY
Revu encode: UTF-8
UTF-8
Revu: H2O AUDIO Waterproof-Ohrhörer Surge Pro Mini BA1-GY
H2O AUDIO Waterproof-Ohrhörer Surge Pro Mini BA1-GY
string(227) "{"id_product":"359805","id_community_ask":null,"barcode":"3000000010907","name":"H2O AUDIO Waterproof-Ohrh\u00f6rer Surge Pro Mini BA1-GY","description":null,"image":null,"status":"2","nb_votes_halal":"0","nb_votes_harram":"0"}"
您可以看到“名称”字段包含一些内容,但是当我在 json 中编码时,它会告诉“null”...我知道 json 仅在 utf8 中有效,这就是为什么我调用 mb_detect_encoding 以确保我在 utf8 中。 ..
知道为什么“name”字段返回“null”吗?
【问题讨论】:
-
能不能在编码后调用json_last_error()看看有没有错误php.net/manual/en/function.json-last-error.php
-
尝试使用:$product->name = iconv("YOURCHARSET","utf8",$product->name);