How to deal with errors in case of a failure in simplexml_load_file in PHP?

Asked

Viewed 444 times

0

I have a routine to access the webservice of the post office that uses simplexml_load_file, but if for some reason the site of the post office is out of air or if it takes too long to answer my site returns an error, then I would like to treat this simplexml_load_file loading error, so that I can present a custom 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;        

3 answers

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 playing an Exception when there is error but if it is not necessary, just adapt to your needs.

  • Nothing yet, I did as you said and the error still continues

0


It seems to me to be a case to use the try{}... catch(){}.

Documentation link: http://php.net/manual/en/language.exceptions.php

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 Finally will always run after a Try catch. If you do not want this behavior, simply remove the block finally

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

-2

if (simplexml_load_file($url)) {
    $xml = simplexml_load_file($url)
    return $xml->cServico;         
} else {
     echo 'SUA MENSAGEM';
}
  • Hello, I did this way you mentioned but it hasn’t worked yet, if xml is not loaded, still showing error

  • I edited the answer. If it doesn’t work try: if (file_exists($url)) { ...

  • It hasn’t worked out yet, tbm tried with if (file_exists($url)) and nothing. There must be some way to treat , to display a more custom error

Browser other questions tagged

You are not signed in. Login or sign up in order to post.