php json_encode 中德语变音的问题

2022-01-07 00:00:00 json character-encoding php

我在处理包含德国变音符号的数据库中的数据时遇到问题.基本上,每当我收到包含变音的数据时,它都是一个带有询问标记的黑色方块.我解决了这个问题

I'm getting troubles with data from a database containing german umlauts. Basically, whenever I receive a data containing umlauts, it is a black square with an interrogation mark. I solved this by putting

mysql_query ('SET NAMES utf8')

在查询之前.

问题是,只要我在查询结果上使用 json_encode(...),包含变音的值就会获得 null.我可以通过直接在浏览器中调用 php 文件来看到这一点.除了在编码为 JSON 并在 JS 中解码之前替换此字符之外,还有其他解决方案吗?

The problem is, as soon as I use json_encode(...) on a result of a query, the value containing an umlaut gets null. I can see this by calling the php-file directly in the browser. Are there other solution than replacing this characters before encoding to JSON and decoding it in JS?

推荐答案

您可能只想在浏览器中以某种方式显示文本,因此一种选择是使用 htmlentities().

You probably just want to show the texts somehow in the browser, so one option would be to change the umlauts to HTML entities by using htmlentities().

以下测试对我有用:

<?php
    $test = array( 'bla' => 'äöü' );
    $test['bla'] = htmlentities( $test['bla'] );

    echo json_encode( $test );
?>

相关文章