我如何在php上使用curl?
curl --get --include 'https://consulta-situacao-cpf-cnpj.p.mashape.com/consultaSituacaoCNPJ?cnpj={cnpj}' \
-H 'X-Mashape-Key: MYKEY'
我知道这是错的,但我尝试了这个(我将MY KEY和MY CPF替换为实际价值):
<?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;
?>
答案 0 :(得分:1)
如果查看curl
的手册页,您会看到-H
选项添加标题,与POST数据无关。要在PHP中执行相同操作,请设置CURLOPT_HTTPHEADER
选项:
<?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;
?>