doushi8599
2016-11-24 11:20
浏览 920
已采纳

使用file_get_contents从url获取JSON

I have a server that provide some data in JSON. I tried to get these data with the usual:

$res = file_get_contents($url);
$result = json_decode($res);
var_dump($result);

But $result is yet a string. The problem is that the data that comes from file_get_content has some alphanumerical string before data and a zero after.

something like:

215ba
{"@attributes":{"ticker":"FCA"},"info...... // here all json data
0

I already checked json validity directly from the url and it's properly formatted, I can not understand where zero and 215ba come from.

Obviously I could strip the strings eliminating both but I was wondering if there was a more concrete solution instead of a workaround

PS: unfortunately I can not use cURL

图片转代码服务由CSDN问答提供 功能建议

我有一台服务器以JSON提供一些数据。 我试图用通常的方式获取这些数据:

  $ res = file_get_contents($ url); 
 $ result = json_decode($ res); 
var_dump($ result)  ); 
   
 
 

但是$ result仍然是一个字符串。 问题是来自file_get_content的数据在数据之前有一些字母数字字符串,之后是零。< / p>

类似于:

  215ba 
 {“@ attributes”:{“ticker”:“FCA”},“info ..  .... //这里所有json数据
0 
   
 
 

我已经直接从网址检查了json有效性并且格式正确,我无法理解零和 215ba来自。

显然我可以删除两个字符串,但我想知道是否有更具体的解决方案而不是解决方法

PS :不幸的是我无法使用cURL

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • dpwdsmbvm496180204 2016-11-24 11:25
    最佳回答

    Note on the docs for json_decode: http://php.net/manual/en/function.json-decode.php

    This function only works with UTF-8 encoded strings..

    Something like this might fix it:

    $contents = file_get_contents($url);
    $contents = utf8_encode($contents);
    $results = json_decode($contents); 
    

    If that's not working you could use regex to check for new lines. Assuming the json will always be on 1 line.

    <?php
    $contents = file_get_contents($url);
    $contents = utf8_encode($contents);
    preg_match('/^.+[
    ](.+)[
    ]./', $contents, $matches);
    
    //the json is in $matches[1]
    print_r($matches);
    
    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题