【发布时间】:2016-07-04 06:07:58
【问题描述】:
我尝试获取这个 json URL 的内容: http://www.der-postillion.de/ticker/newsticker2.php
问题似乎是“文本”的内容中包含 Unicode。
每次我尝试获取 json_decode 时,它都会以 NULL 失败...以前从未遇到过这个问题。总是这样拉 json:
$news_url_postillion = 'http://www.der-postillion.de/ticker/newsticker2.php';
$file = file_get_contents($news_url_postillion, false, $context);
$data = json_decode($file, TRUE);
//debug
print_r(array($data));
$news_text = $data['tickers'];
//test
echo $news_text->text[0]; //echo first text element for test
foreach($news_text as $news){
$news_text_output = $news->{'text'};
echo 'Text:' . echo $news_text_output; . '<br>';
}
有人知道这里有什么问题吗?尝试通过以下方式使编码工作数小时:
header("Content-Type: text/json; charset=utf-8");
或
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content: type=application/json\r\n" .
"Content-Type: text/html; charset=utf-8"
)
);
$context = stream_context_create($opts);
但没有运气:(
感谢您的帮助!
解决方案:
json 源中有一些不需要的元素,例如 json 开头的 BOM 字符。我无法影响源 json,因此 walkingRed 提供的解决方案让我走上了正轨。由于他的代码仅适用于没有特殊字符的英语,因此只需要 utf8_decode。
我用于解析和输出 json 的工作代码解决方案是:
<?php
// Postillion Newsticker Parser
$news_url_postillion = 'http://www.der-postillion.de/ticker/newsticker2.php';
$json_newsDataPostillion = file_get_contents($news_url_postillion);
// Fix the strange json source BOM stuff
$obj_newsDataPostillion = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_newsDataPostillion), true);
//DEBUG
//print_r($result);
foreach($obj_newsDataPostillion['tickers'] as $newsDataPostillion){
$newsDataPostillion_text = utf8_decode($newsDataPostillion['text']);
echo 'Text:' . $newsDataPostillion_text . '<br>';
};
?>
【问题讨论】:
-
你检查
json_last_error了吗? php.net/manual/en/function.json-last-error.php -
在尝试解析 JSON 之前,您是否尝试过运行 utf8_decode()? php.net/manual/en/function.utf8-decode.php
-
你的
$context = stream_context_create()呢?? -
感谢您的猜测,我添加了我的解决方案。 walkRed 的答案 1 让我走上了正确的道路。
标签: php json unicode-normalization