PHP JSON 请求:json_decode Unicode 字符串


php json request: json_decode unicode string

我尝试获取此json网址的内容: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>';
};
?>

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

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

原始帖子

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

您可以看到它,例如,如果您使用 wget 下载该 json 并以更少的速度显示它。