【问题标题】:'file_get_contents' function from multiple URLs and redirection limit reached warning来自多个 URL 的“file_get_contents”函数和重定向限制达到警告
【发布时间】:2019-05-24 08:09:31
【问题描述】:

我需要从多个 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 警告?

【问题讨论】:

  • 您似乎将$context 的值设置了两次。您没有向我们展示您的示例中的 $opts 是什么,所以这可能是不正确的,因为这就是您的 $context 设置的内容。
  • 感谢您的指出。我忘了删除来自先前替代解决方案的$context = stream_context_create($opts);。它与标题选项有关。

标签: php json url decode


【解决方案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;
}

【讨论】:

  • 感谢您的建议。我需要一一解析 JSON 文件。当我回显结果时,它会给出所有结果。另外,请您告诉我您为什么建议使用 cURL 吗?有什么比 file_get_contents 函数更好的功能?
  • @MadameGreenPea cURL 为您提供了更多标题选项 (see here),我编辑了我的答案以遵循重定向。至于一个一个显示文件的内容,我编辑了我的答案只做第一个($decoded[0],如果你想要URL,它将是$urls[0]
  • 非常感谢! @blex
猜你喜欢
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
  • 2019-02-27
  • 2019-10-31
相关资源
最近更新 更多