我试图让这个JSON URL的内容: http://www.der-postillion.de/ticker/newsticker2.phpPHP的JSON请求:json_decode unicode字符串
问题似乎是的“文本”的内容中使用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 start的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/en/function.json-last-error.php – Arno
在尝试解析JSON之前,您是否尝试过运行utf8_decode()? http://php.net/manual/en/function.utf8-decode.php –
你的'$ context = stream_context_create()'在哪里? – RiggsFolly