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 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面