如果出现错误,则跳过当前循环


Jumping over the current loop, if error

我有

foreach($users as $user){ 
            $doc = new DOMDocument();
            $doc->loadXml(file_get_contents($user["syncUrl"]));
}

如果$user["syncUrl"]上的url中的内容,那么loadXml()会返回错误(如果它无法读取),我希望它继续;在下一个循环(next$user)之前,不要阅读循环中的其余部分。

现在它正在崩溃,并且输出由于格式错误而无法读取的内容。但我希望它跳过这个,然后继续剩下的。

我该怎么做?

Hehe,您的问题是:continue;是跳过循环其余部分并开始下一次迭代的命令。对$doc->loadXML进行错误检查,如果它没有成功加载,则continue;

因此:

foreach($users as $user)
{ 
     $doc = new DOMDocument();
     $loaded = $doc->loadXml(file_get_contents($user["syncUrl"])); //Should return false on failure, true on success
     if($loaded === false)
     {
         continue;
     }
     //Do other stuff here if successfully loaded.
}

使用DOMDocument::validate()来验证格式(来自DTD),如果continue无效,也可能是明智的。还可以使用DOMDocument::schemaValidateSource()提供源模式,并使用DOMDocument::schemaValidate()验证该模式中的格式。您也可以这样做以在加载时对其进行验证:

$doc = new DOMDocument();
$doc->validateOnParse = true;
$doc->loadXML('etc');

如果文件内容确实存在,那么加载函数返回false可能是必要的。

试着在$doc->loadXml调用前面放一个@,看看这是否有效。

使用错误抑制运算符@:

foreach($users as $user) { 
    $doc = new DOMDocument();
    @$doc->loadXml(file_get_contents($user["syncUrl"]));
}

使用try-and-catch块?

foreach($users as $user){ 
    try{
        $doc = new DOMDocument();
        $doc->loadXml(file_get_contents($user["syncUrl"]));
    }
    catch(Exception $e){
        continue;
    }
    //Rest of the code..
}