I want to save a return of a function in php within a variable

Asked

Viewed 708 times

0

Hello,

I have the following problem,

I have a code in php, where I declare a function to search for zip on the mail server, in this function returns me a json depending on the zip I report.

now I want to keep it in a variable but I’m not succeeding, when gugardar it displays the return of function without me wanting.

how do I treat it?

follows the function;

function obterLogradouro($cep)
{

$html = simple_curl('http://m.correios.com.br/movel/buscaCepConfirma.do',array(
    'cepEntrada'=>$cep,
    'tipoCep'=>'',
    'cepTemp'=>'',
    'metodo'=>'buscarCep'
));

phpQuery::newDocumentHTML($html, $charset = 'utf-8');
$errCEP= array('erro'=> trim(pq('.erro:eq(0)')->html()));

if(empty($errCEP["erro"])){

    $dados =
    array(
    'logradouro'=> trim(pq('.caixacampobranco .resposta:contains("Logradouro: ") + .respostadestaque:eq(0)')->html()),
    'bairro'=> trim(pq('.caixacampobranco .resposta:contains("Bairro: ") + .respostadestaque:eq(0)')->html()),
    'cidade/uf'=> trim(pq('.caixacampobranco .resposta:contains("Localidade / UF: ") + .respostadestaque:eq(0)')->html()),
    'cep'=> trim(pq('.caixacampobranco .resposta:contains("CEP: ") + .respostadestaque:eq(0)')->html())
    );

    $dados['cidade/uf'] = explode('/',$dados['cidade/uf']);
    $dados['cidade'] = trim($dados['cidade/uf'][0]);
    $dados['uf'] = trim($dados['cidade/uf'][1]);
    unset($dados['cidade/uf']);

    die(json_encode($dados));

}else{

echo "CEP não localizado!!!";

}

}

And now as I’m trying to hold on;

$dadocep= 91250000;

$var=get Ogradouro($dadocep);

but in doing so I want to treat and not display.

thank you!

1 answer

3


Have you tried it instead of

die(json_encode($dados));

do

return json_encode($dados);

and in case of failure

return "CEP não localizado!!!";

you’re not giving the return function so its variable is empty;

  • Only complementing the answer: if you are using PHP 7 it is possible to trigger an exception of ZIP code not found, otherwise the return could be done as suggested by Fernando or even the NULL value, considering the appropriate treatment in the upper layer.

Browser other questions tagged

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