2016-03-17 127 views
3

我试图让这个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>'; 
}; 
?> 
+0

你检查'json_last_error'? http://php.net/manual/en/function.json-last-error.php – Arno

+0

在尝试解析JSON之前,您是否尝试过运行utf8_decode()? http://php.net/manual/en/function.utf8-decode.php –

+0

你的'$ context = stream_context_create()'在哪里? – RiggsFolly

回答

1

我做了一些搜索和得到这个:

$result = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $file), true); 

Original post

+0

,让我走上正轨!非常感谢你。这不是直接可用的,因为我的字符串中包含特殊字符,这是因为德语,并且您的解决方案会杀死特殊字符,但我使用上述代码修复了这些字符。最重要的是,您的解决方案为我提供了所需的有效数组输出:-) – MonkeyKingFlo

+0

@MonkeyKingFlo搜索期间我发现德文字符在json编码/解码中非常棘手。对你有些新东西对我来说是新的:) – walkingRed

0

BOM!在链接文档的开头处有一个BOM字符,您需要在尝试解码其内容之前将其删除。

你可以看到它,例如如果你想用wget下载这个json并用较少的显示。

+0

是的,谢谢,那就对了!我忽略了......你的回答和行走红色的答案让我走上了正确的轨道!所以谢谢! – MonkeyKingFlo