douliudong8108 2012-05-03 19:41
浏览 300
已采纳

无法使用file_get_contents()以正确的格式获取json

I parse a parameter to a php file and try to get json with file_get_contents(). This is my Code:

< ?php
    $url = $_GET['url'];
    $url = urldecode($url);
    $json = file_get_contents($url, true);
    echo($json);
? >

This is the called URL: http://vimeo.com/api/v2/channel/photographyschool/videos.json

This is a part of my result:

[{"id":40573637,"title":"All For Nothing - \"Dead To Me\" & \"Twisted Tongues\""}]

And so on... So everything is escaped. There are even in the result.

Since I neet to work afterwards with the json (in js), I need a non escaped version!

Interesting thing is, that my code works for example with this json: http://xkcd.com/847/info.0.json

What is my problem?

  • 写回答

4条回答 默认 最新

  • dongmaobeng7145 2012-05-03 19:53
    关注

    If you just want to proxy/forward the response then just echo it as it is with the correct Content-Type header:

    <?php
        header('Content-Type: application/json');
        $json = file_get_contents('http://vimeo.com/api/v2/channel/photographyschool/videos.json');
        echo $json;
    ?>
    

    Tho you have to be very wary of the url passed as it could cause XSS!

    And as the API is slow/resource hungry you should cache the result or at least save it in a session so its not repeated on each page load.

    <?php
    $cache = './vimeoCache.json';
    $url = 'http://vimeo.com/api/v2/channel/photographyschool/videos.json';
    
    //Set the correct header
    header('Content-Type: application/json');
    
    // If a cache file exists, and it is newer than 1 hour, use it
    if(file_exists($cache) && filemtime($cache) > time() - 60*60){
        echo file_get_contents($cache);
    }else{
        //Grab content and overwrite cache file
        $jsonData = file_get_contents($url);
        file_put_contents($cache,$jsonData);
        echo $jsonData;
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图