我尝试获取此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>';
};
?>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句