dongmin3754 2011-01-21 16:47
浏览 43
已采纳

为什么php的file_get_contents错误地从xkcd中检索json文件?

In writing a PHP script to download xkcd comics, i incurred errors when trying to get specific comics (as opposed to the latest one). Specifically, pointing file_get_contents at the following url:

xkcd.com/$COMIC_NUM/info.0.json

inexplicably retrieved the xhtml version of the comic's page on xkcd.com, and not a JSON file. However, if i request the exact same url in my browser, the correct JSON file is downloaded. I'm not sure why this is happening, but i suspect it has something to do with the request headers being sent.

Please help! :S

  • 写回答

2条回答 默认 最新

  • drnysdnnb2909701 2011-01-21 16:55
    关注

    Whilst I it personally works perfectly with file_get_contents for me, you could try using cURL as follows (if you have it available) as this would be a more robust solution:

    <?php
        $COMIC_NUM = 849;
    
        $curlSession = curl_init();
        curl_setopt($curlSession, CURLOPT_URL, '"http://xkcd.com/'.$COMIC_NUM.'/info.0.json');
        curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
        $jsonData = curl_exec($curlSession);
        curl_close($curlSession);
    
        echo($jsonData);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料