doushi8599
doushi8599
2016-11-24 11:20

使用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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dpwdsmbvm496180204 dpwdsmbvm496180204 5年前

    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);
    
    点赞 评论 复制链接分享
  • drl6054 drl6054 5年前

    The problem you have been facing I very common, ideally this occurs when json data isn't wellformed such as an unsupported charset included in string or some broken string. Therefore simply try to decode you file contents with UTF-8 support just to be on safer side and less complicating your problem you could either do it with using utf8_encode() function in php or using curl to process the utf-8 contents obtained through file.

    点赞 评论 复制链接分享
  • dougui4325 dougui4325 5年前

    could it be that the JSON contains UTF8 characters, so is using a BOM marker at the beginning of the file, and your json_decode function is running in PHP that does not have multi-byte strings enabled?

    点赞 评论 复制链接分享

相关推荐