来自多个网址的“ file_get_contents”功能和重定向限制已达到警告

时间:2018-12-25 21:18:28

标签: php json url decode

我需要从多个URL解析JSON。这是我遵循的方式:

<?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>';
                    }
                }
            }
?>

这样会导致页面打开速度变慢。另一方面,我得到这些错误:

  

警告:file_get_contents(https://www.url1.com):打开失败   流:已达到重定向限制,正在中止   /home/directory/public_html/file.php,第12行

     

警告:file_get_contents(https://www.url2.com):打开失败   流:已达到重定向限制,正在中止   /home/directory/public_html/file.php,第13行

     

如何解决redirection limit reached警告?

1 个答案:

答案 0 :(得分:1)

我建议使用cURL来获取远程数据。您可以这样做:

$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;
}