duangang2825 2018-05-23 14:24
浏览 88
已采纳

循环一个file_get_contents直到在php中获得非空的JSON

I have the following code:

<?php
$json = file_get_contents("https://api.nanopool.org/v1/eth/payments/0x218494b2284a5f165ff30d097d3d7a542ff0023B");
$decode = json_decode($json,true);
foreach($decode['data'] as $val){   
 echo date('Y-m-d',$val['date']).' -- '.$val['amount'].' -- '.$val['txHash'].' -- '.$val['confirmed'];
   echo "<br/>";
 }

The API used (nanopool) being extremely unreliable, I get a non empty json (success) every 2 to 10 calls.

I tried to loop the file_get_contents (do... while) until getting a non empty json without success. What can you recommend to loop until I get an answer?

  • 写回答

1条回答 默认 最新

  • dousi4148 2018-05-23 14:57
    关注

    Maybe you can try something like this, still I don't recommend using this within a synchronous script (eg a web page) because you can't control the time needed to get a successfull answer.

    <?php
    function getFileFTW($url)
    {
        $fuse = 10;//maximum attempts
        $pause = 1;//time between 2 attempts
        do {
            if($fuse < 10)
                sleep($pause);
            $s = @file_get_contents($url);
        }
        while($s===false && $fuse--);
        return $s;
    }
    
    
    $json = getFileFTW("https://api.nanopool.org/v1/eth/payments/0x218494b2284a5f165ff30d097d3d7a542ff0023B");
    if($json) {
        $decode = json_decode($json,true);
        //...
    }
    else {
        //json not loaded : handle error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vscode问题请教
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM