【问题标题】:php file_get_contents from different URL if first one not available如果第一个不可用,则来自不同 URL 的 php file_get_contents
【发布时间】:2016-07-20 10:41:37
【问题描述】:

我有以下代码来读取一个在 URL 可用时运行良好的 XML 文件:

$url = 'http://www1.blahblah.com'."param1"."param2";

$xml = file_get_contents($url);

$obj = SimpleXML_Load_String($xml);

如果第一个 URL 因任何原因不可用,我如何更改上述代码以循环访问多个不同的 URL?我有一个包含相同文件的 4 个 URL 的列表,但我不确定如何去做。

【问题讨论】:

  • 对于一个快速而肮脏的解决方案,您需要一个 while 循环和一个可能的 url 数组

标签: php xml file-get-contents


【解决方案1】:

用例如这个替换你的代码

//instead of simple variable use an array with links
$urls = [   'http://www1.blahblah.com'."param1"."param2",
            'http://www1.anotherblahblah.com'."param1"."param2",
            'http://www1.andanotherblahblah.com'."param1"."param2",
            'http://www1.andthelastblahblah.com'."param1"."param2"];

//for all your links try to get a content
foreach ($urls as $url) {
    $xml = file_get_contents($url);

    //do your things if content was read without failure and break the loop
    if ($xml !== false) {
        $obj = SimpleXML_Load_String($xml);
        break;
    }
}

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 2021-10-12
    • 2015-08-24
    相关资源
    最近更新 更多