【发布时间】:2016-11-17 13:27:01
【问题描述】:
我得到了一个在 python 程序中生成的 json,它看起来像这样:
{"0": {"ausschreiber": "Beispiel; Zeitarbeit GmbH", "beschreibung": "\r\nF\u00fcr unseren Kunden suchen wir motivierte studentische Aushilfen auf flexibler Stundenbasis (450\u0080-Basis)", "datum": "17.11.2016", "name": "Studentische Hilfskr\u00e4fte gesucht", "email": "info@hindi.de"}}
现在我正在对我的 php 程序中的 json 进行解码以获取关联数组并将其显示在网站上。 问题是像 € 字符这样的特殊字符没有显示,但是像 ö ä ü 这样的特殊字符被显示了。 这是php程序:
<?php
header('Content-Type: text/html; charset=utf-8');
function compare($old_data, $new_data){
$old_result = json_decode($old_data, true);
$new_result = json_decode($new_data, true);
echo $new_result[0]['beschreibung'];
}
function go4it(){
$db_data=json_content(); //creates the json from the Database
$crawler_data = file_get_contents('http://localhost/phppath/python_program.cgi'); //calls the cgi which returns the json
compare($db_data, $crawler_data);
}
go4it();
我尝试了什么:
- 将标头设置为 utf-8
$new_result = json_decode(utf8_encode($new data), true);iconv_set_encoding("internal_encoding", "UTF-8");iconv_set_encoding("input_encoding", "UTF-8");iconv_set_encoding("output_encoding", "UTF-8");
感谢您的帮助!
编辑 1 所以看起来问题出在python程序中,感谢@FranzGleichmann。我认为问题在于我从中获取内容的页面的编码。该页面说它是 ISO-8859-1,所以我尝试了这个:
url = 'https://www.example.com'
source_code = requests.get(url)
plain_text = source_code.text
plain_text.decode('iso-8859-1', 'ignore').encode('utf8', 'ignore')
print(plain_text.encoding)
但随后我收到错误消息:“UnicodeEncodeError:'ascii' 编解码器无法在位置 8496 编码字符 u'\xf6':序数不在范围内 (128)”
【问题讨论】:
-
您发布的 JSON 无效
-
您的生成脚本似乎使用了一些错误的字符集或其他什么。它升级为
\u0080- 它应该是\u20ac。 -
@Nordenheim 现在它是有效的,不是吗? json 更长,所以我缩短了它。
-
@JeremyHarris 我认为 JSON_UNESCAPED_UNICODE 只是用于编码,但我正在解码 json
-
@FranzGleichmann 是的,我的 python 程序生成了这个输出,所以问题出在哪里?
标签: php json utf-8 special-characters decoding