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.

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

报告相同问题?

悬赏问题

  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化