php file_get_contents 来自不同 URL 如果第一个不可用

php file_get_contents from different URL if first one not available

我有以下代码来读取 XML 文件,当 URL 可用时它运行良好:

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

$xml = file_get_contents($url);

$obj = SimpleXML_Load_String($xml);

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

用例如这个替换你的代码

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