doujiu3097 2018-12-25 21:18
浏览 229
已采纳

来自多个URL的'file_get_contents'函数和重定向限制已达到警告

I need to parse JSON from multiple URLs. Here is the way that I'm following:

<?php
//call
$url1 = file_get_contents("https://www.url1.com");
$url2 = file_get_contents("https://www.url2.com");
$url3 = file_get_contents("https://www.url3.com");
$url4 = file_get_contents("https://www.url4.com");
$url5 = file_get_contents("https://www.url5.com");
//parse
$decode1 = json_decode($url1, true);
$decode2 = json_decode($url2, true);
$decode3 = json_decode($url3, true);
$decode4 = json_decode($url4, true);
$decode5 = json_decode($url5, true);

//echo 
if (is_array($decode1)) {
                foreach ($decode1 as $key => $value) {
                    if (is_array($value) && isset($value['price'])) {
                        $price = $value['price'];
                        echo '<span><b>' . $price . '</b><span>';
                    }
                }
            }
?>

This way causes slowness in the page openings. On the other hand, I get these errors:

Warning: file_get_contents(https://www.url1.com): failed to open stream: Redirection limit reached, aborting in /home/directory/public_html/file.php on line 12

Warning: file_get_contents(https://www.url2.com): failed to open stream: Redirection limit reached, aborting in /home/directory/public_html/file.php on line 13

etc.

How can I fix the redirection limit reached warning?

  • 写回答

1条回答 默认 最新

  • dpxo13079 2018-12-25 21:32
    关注

    I would suggest using cURL for fetching remote data. You could do this:

    $urls = [
        "https://www.url1.com",
        "https://www.url2.com",
        "https://www.url3.com",
        "https://www.url4.com",
        "https://www.url5.com"
      ];
    $decoded = array_map("loadJSON", $urls);
    
    if (is_array($decoded[0])) {
      foreach ($decoded[0] as $key => $value) {
        if (is_array($value) && isset($value['price'])) {
          $price = $value['price'];
          echo '<span><b>' . $price . '</b><span>';
        }
      }
    }
    
    /**
     * Downloads a JSON file from a URL and returns its decoded content
     */
    function loadJSON($url) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // If your server does not have SSL
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Follow redirections
      curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // 10 max redirections
      $content = curl_exec($ch);
      curl_close($ch);
      $res = json_decode($content, true);
      return $res;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器