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

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

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?