How to prevent a method from printing data when calling a third-party API?

Asked

Viewed 269 times

10

I’m using an API and in some cases a feature of it prints on the screen when there are errors (api errors, not PHP). I happen to call this API via AJAX and it breaks my code since the request ends up generating an invalid JSON.

Is there any way to avoid this in PHP? For example, from a certain chunk of code to another chunk, nothing is printed on the screen?

Something like that:

// desativaria impressão de qualquer coisa aqui
$this->soapClient = new SoapClient($wsdlLink);
$retorno = $this->soapClient->testFunction($params);
// ativaria impressão aqui

In the above case when I call testFunction, instead of saving the error in the $return variable, it prints on the screen.

When accessing a SOAP resource you are calling a pre-set function by the SOAP API developer. It turns out that sometimes testFunction prints the direct error and not as callback.

What to do to solve this problem?

  • Just to be on the lookout: this question has nothing to do with SOAP or catching errors or exceptions.

3 answers

13


You can use the Output Buffer PHP to capture output without sending to client:

ob_start(); 
$this->soapClient = new SoapClient($wsdlLink);
$retorno = $this->soapClient->testFunction($params);
$output_retido = ob_get_contents(); //opcional, caso queira usar o que foi retido
ob_end_clean();
  • Thank you Bacco. It worked as I wanted.

4

Has a gambit to inhibit the impression of mistakes on own core PHP, which is to use error control operator @ before the command:

$retorno = @$this->soapClient->testFunction($params);
  • 1

    testFunction is an API resource via Soap. If the API developer wants to print it, it will end up appearing in my ajax request. It is not a PHP error.

  • 2

    What do you mean? If you say that "instead of saving the error in the $return variable, it prints on the screen", the error would be php. You can clarify this?

  • Have you even tested my suggestion? By what you’re saying, the @ should delete the error. @rodrigoum

3

Utlizando display_errors it is possible to hide/display errors at runtime in a specific script.

ini_set('display_errors', false);
$this->soapClient = new SoapClient($wsdlLink);
$retorno = $this->soapClient->testFunction($params);
ini_set('display_errors', true);
  • 1

    It is not a PHP error. It is an error that the API itself commands.

Browser other questions tagged

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