我試圖讓這個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