【问题标题】:php json request: json_decode unicode string [duplicate]php json请求:json_decode unicode字符串[重复]
【发布时间】:2016-07-04 06:07:58
【问题描述】:

我尝试获取这个 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>';
};
?>

【问题讨论】:

标签: php json unicode-normalization


【解决方案1】:

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

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

Original post

【讨论】:

  • 这让我走上了正轨!非常感谢您。它不能直接使用,因为由于德语,我的字符串中有特殊字符,而您的解决方案会杀死特殊字符,但我用上面的代码修复了这个问题。最重要的是,您的解决方案为我提供了所需的有效数组输出:-)
  • @MonkeyKingFlo 在搜索过程中我发现德语字符在 json 编码/解码中非常棘手。对你来说新的东西对我来说是新的:)
【解决方案2】:

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

你可以看到它,例如如果你想用 wget 下载那个 json 并用 less 显示它。

【讨论】:

  • 是的,谢谢,没错!我忽略了……您的回答和walkingRed的回答使我走上了正轨!所以谢谢你!
猜你喜欢
  • 2013-08-18
  • 1970-01-01
  • 2019-03-15
  • 2023-04-09
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 2011-04-08
相关资源
最近更新 更多