我尝试获取这个json URL的内容:http://www.der-postillion.de/ticker/newsticker2.php。问题似乎是“text”中包含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
吗? http://php.net/manual/zh/function.json-last-error.php - Arno$context = stream_context_create()
在哪里? - RiggsFolly