0

我有一个要在 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"}"

你可以看到'name'字段包含一些东西,但是当我在json中编码时它告诉'null'......我知道json只在utf8中工作,这就是为什么我调用mb_detect_encoding来确保我在utf8中......

知道为什么“名称”字段返回“空”吗?

4

1 回答 1

0

您需要执行以下任一操作:

mb_convert_encoding($product->name,"utf8","THE_NAME_CHARSET");

或者:

$product->name = iconv("THE_NAME_CHARSET","utf8",$product->name);
于 2012-06-01T08:37:56.490 回答