duanlaofu4108 2014-09-04 19:58
浏览 119
已采纳

为什么我的函数发送多个cURL请求失败?

I have this function, historicalBootstrap, which I want to use to put three different datasets into a page:

$years = array(
        date('Y-m-d', strtotime('1 year ago')). ".json",
        date('Y-m-d', strtotime('2 years ago')). ".json",
        date('Y-m-d', strtotime('3 years ago')). ".json"    
    );

function historicalBootstrap($years, $id){

    for($i = 0; $i < 3; $i++){

        $date = $years[$i]; 

        $i = curl_init("http://openexchangerates.org/api/historical/{$date}?app_id={$id}");
        curl_setopt($i, CURLOPT_RETURNTRANSFER, 1);

        $jsonHistoricalRates = curl_exec($i);
        curl_close($i);

        $i = json_decode($jsonHistoricalRates);
        echo '<script>_'. $i . 'historical = '. json_encode($historicalRates) . ' ; ' . '</script>';

    }   
}

historicalBootstrap($years, $appId);

It seems I can use this approach to make one request, e.g. outside of the function block. Why is it that when I abstract this approach into the historicalBootstrap function that it fails? I am expecting three (_0 = ... , _1 = ... , _2 = ...) bootstrapped scripts.

Thank you.

  • 写回答

1条回答 默认 最新

  • dousao9569 2014-09-04 20:07
    关注

    You are using $i to control your for loop and also to contain the curl handle and also to contain a json decode result.

    You are also decoding the returned json and then straight away encoding it again, not necessary.

    Try changing it to

    function historicalBootstrap($years, $id){
    
        for($i = 0; $i < 3; $i++){
            $date = $years[$i]; 
            $ch = curl_init("http://openexchangerates.org/api/historical/{$date}?app_id={$id}");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $jsonHistoricalRates = curl_exec($ch);
            curl_close($ch);
            echo '<script>_'. $i . 'historical = '. $jsonHistoricalRates . ';' . '</script>';
        }   
    }
    

    You could also make this more flexible by using foreach() instead of for

    function historicalBootstrap($years, $id){
        foreach ($years as $i => $year) {
            $ch = curl_init("http://openexchangerates.org/api/historical/{$year}?app_id={$id}");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $jsonHistoricalRates = curl_exec($ch);
            curl_close($ch);
            echo '<script>_'. $i . 'historical = '. $jsonHistoricalRates . ';' . '</script>';
        }   
    }
    

    Now if you pass 4 years into the function it will not require amending this code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装