Search code examples
phpcurlmashape

How i use mashape curl on php


How i use it on php with curl?

curl --get --include 'https://consulta-situacao-cpf-cnpj.p.mashape.com/consultaSituacaoCNPJ?cnpj={cnpj}' \
  -H 'X-Mashape-Key: MYKEY'

I know this is wrong but i try this (I replace MY KEY and MY CPF for real values):

<?php
$cpf = "MY CPF";
$url = "https://consulta-situacao-cpf-cnpj.p.mashape.com/consultaSituacaoCPF?cpf=".$cpf;
$data = array('X-Mashape-Key' => 'MY KEY'); //My Key

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$name = trim(curl_exec($curl));
curl_close($curl);

echo $name;
?>

Solution

  • If you look at the man page for curl you'll see that the -H option adds a header, nothing to do with POST data. To do the same in PHP, set the CURLOPT_HTTPHEADER option:

    <?php
    $cpf = "MY CPF";
    $url = "https://consulta-situacao-cpf-cnpj.p.mashape.com/consultaSituacaoCPF?cpf=".$cpf;
    $headers = array("X-Mashape-Key: MY KEY"); //My Key
    
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL,$url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $name = trim(curl_exec($curl));
    curl_close($curl);
    
    echo $name;
    ?>