http_build_query function

0

I'd like to know what the http_build_query function in php is for. I read the manual, but it became vague to me.

link

Is it right to use it within this context?

    $cURL = curl_init('http://teste');
    curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
    $dados = array(
            'NMCLIENTE' => $nome_lead,
            'DSEMAIL' =>  $email_lead,
            'NRTELEFONE' => $telefone_lead,
            'DSINTERESSE' => $meio_captacao,
            'DSMENSAGEM' => $mensagem
            );
    curl_setopt($cURL, CURLOPT_POST, true);

    curl_setopt($cURL, CURLOPT_POSTFIELDS,  http_build_query($dados));

    $resultado = curl_exec($cURL);
    curl_close($cURL);
    
asked by anonymous 27.04.2015 / 15:27

1 answer

5

Nothing is more than turning your array into a querystring format, ready for be passed to a URL . It will transform the key-value sequence and separate it by a & .

It simplifies the process of:

  • Concatenate each key-value with a & (as would be done with implode() );
  • Encode the URL (as would be done with urlencode() ) where all non-alphanumeric characters are replaced by a % sign followed by two hexadecimal characters and spaces encoded with a + sign;
  • About using in this context that you have demonstrated is correct but not necessary since you are advising that you will send the request through the POST method since CURLOPT_POST is true. This way, you can pass both a array and a URL-like string to%

    When you pass the array directly, the CURLOPT_POSTFIELDS of the request will automatically be Content-type , whereas if you pass a string, it will be multipart/form-data .     

    27.04.2015 / 15:59