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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助