donglizhan7848 2016-12-27 18:30
浏览 56
已采纳

无法通过网址从URL解码json

I am trying to read json vi php but unable to decode

<?php 
$json_url = "http://chartapi.finance.yahoo.com/instrument/1.0/AAPL/chartdata;type=quote;range=5d/json";
$json = file_get_contents($json_url);

$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";

?>
  • 写回答

3条回答 默认 最新

  • douduan5753 2016-12-27 18:45
    关注

    If you visit your target URL you will notice the JSON value is wrapped in a callback method which you could trim as by something like

    $json = str_replace('finance_charts_json_callback(', '', substr($pageContent, 0, strlen($pageContent) - 1));
    

    Here is how it looks all put together:

    <?php 
    $json_url = "http://chartapi.finance.yahoo.com/instrument/1.0/AAPL/chartdata;type=quote;range=5d/json"; $pageContent = file_get_contents($json_url);
    
    $json = str_replace('finance_charts_json_callback(', '', substr($pageContent, 0, strlen($pageContent) - 1));
    
    $data = json_decode($json, TRUE);
    
    echo "<pre>"; print_r($data); echo "</pre>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • douhuan3448 2016-12-27 18:41
    关注

    One thing you can do is work with it in JavaScript:

    <script>
    function finance_charts_json_callback(json){
        console.log(json.meta);
    }
    </script>
    
    <?php 
    $json_url = "http://chartapi.finance.yahoo.com/instrument/1.0/AAPL/chartdata;type=quote;range=5d/json";
    $data = file_get_contents($json_url);
    
    echo "<script>";
    print_r($data);
    echo "</script>";
    ?>
    

    Other thing is try to remove the 'function' part:

    <?php 
    $json_url = "http://chartapi.finance.yahoo.com/instrument/1.0/AAPL/chartdata;type=quote;range=5d/json";
    $json = file_get_contents($json_url);
    $json = substr($json, 30);
    $json = substr($json, 0, strlen($json)-2);
    $data = json_decode($json, TRUE);
    echo "<pre>";
    print_r($data);
    echo "</pre>";
    
    ?>
    
    评论
  • duanjing3656 2016-12-27 18:42
    关注

    The response from this service is not a valid JSON object its JSONP, you should look for a service that provides output as JSON.

    In case they don't provide a service like that you can manipulate the data before decoding it using this workaround

    $data = str_replace('finance_charts_json_callback( ', '', $data);
    $data = str_replace(' )', '', $data);
    
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 易语言编写cs.16 绘制 矩阵出现了点问题 不知道这个矩阵可不可以使用
  • ¥15 k210显示failed init to model
  • ¥15 Evil-droid生成的APK手机已经下载但无法建立任务
  • ¥25 c语言韩信点兵的变式
  • ¥15 怎么根据书上的例子完成这个问题呢?
  • ¥15 ECharts 增加Zoom,整行包括右边的Text一起滑动
  • ¥15 关于网上一个easyx制作的见缝插针小游戏(c++)
  • ¥15 开地址法双散列函数处理碰撞
  • ¥15 想问一下这个是什么情况 虚拟机Linux打不开了
  • ¥15 联通光猫掉注册了怎么重新注册上去