How to handle errors in simplexml_load_file in PHP? [duplicate]

0

I have a routine to access the webservice of the mails that uses simplexml_load_file, but if for some reason the post office website is out of order or if it takes too long to respond to my site it returns an error, then I would like to handle this error of loading the simplexml_load_file, so that I can present a personalized message to the user, tried in some ways more unsuccessfully, follow my current code:

    $url = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?";
    $url .= "nCdEmpresa=" . $cod_administrativo;
    $url .= "&sDsSenha=" . $senha;
    $url .= "&sCepOrigem=" . $cep_origem;
    $url .= "&sCepDestino=" . $cep_destino;
    $url .= "&nVlPeso=" . $peso;
    $url .= "&nVlLargura=" . $largura;
    $url .= "&nVlAltura=" . $altura;
    $url .= "&nCdFormato=1";
    $url .= "&nVlComprimento=" . $comprimento;
    $url .= "&sCdMaoPropria=" . $mao_propria;
    $url .= "&nVlValorDeclarado=" . $valor;
    $url .= "&sCdAvisoRecebimento=" . $aviso_recebimento;
    $url .= "&nCdServico=" . $servico;
    $url .= "&nVlDiametro=0";
    $url .= "&StrRetorno=xml";

    $xml = simplexml_load_file($url);    

    if ($xml === false || $xml === 0 || $xml === "") {

        return '';
    }

    return $xml->cServico;        
    
asked by anonymous 19.09.2018 / 14:07

3 answers

0

It seems like a case to use try{}... catch(){} .

Documentation link: link

try {
    $xml = simplexml_load_file($url)
} catch (Exception $e) {
    echo 'Exceção capturada: ',  $e->getMessage(), "\n";
} finally {
    echo "Código que será executado após o try catch.";
}

An important note about the code snippet above is that the finally will always run after a try catch. If you do not want this behavior, just remove block finally

Update: This code snippet seems to work correctly only in PHP7 version or later.

    
19.09.2018 / 19:53
0

This should work here, but if you want something more robust I suggest using a third party component that loads xml.

// nescessário pra consegui pegar os errors
libxml_use_internal_errors(true);
$xml = simplexml_load_file($filePath);
if ($xml === false) {
    $message = '';
    foreach (libxml_get_errors() as $error) {
        $message .= $error->message;
    }
    throw new Exception(trim($message));
}

Note: Here he is throwing an exception when he has an error, but if it is not necessary, he is only adptar for his needs.

    
19.09.2018 / 19:38
-2
if (simplexml_load_file($url)) {
    $xml = simplexml_load_file($url)
    return $xml->cServico;         
} else {
     echo 'SUA MENSAGEM';
}
    
19.09.2018 / 14:54