我正在尝试将此命令移植到PHP:
curl -i -X POST http://website.com \
-H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
-H "Accept: Application/json" \
-H "X-Requested-With: XMLHttpRequest" --data "var1=output1&var2=output2"
从bash开始工作..我得到 this JSON输出。
这是我在PHP中编写的尝试获得相同结果的内容:
<?php
function blabla() {
$curl_parameters = array(
'var1' => "output1",
'var2' => "output2",
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://website.com");
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query( $curl_parameters ));
curl_setopt($ch,CURLOPT_HTTPHEADER,array (
"Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8",
"Accept" => "Application/json",
"X-Requested-With" => "XMLHttpRequest",
));
$output=curl_exec($ch);
curl_close($ch);
}
echo blabla();
?>
不幸的是,对于这个片段,我只得到一个302 Found HTTP头作为输出(this)..似乎没有传递变量(来自bash命令的--data
部分)。
答案 0 :(得分:1)
问题在于您的CURLOPT_HTTPHEADER
。它应该是一个像这样的字符串数组:
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
'Accept: application/json',
'X-Requested-With: XMLHttpRequest',
));
答案 1 :(得分:0)
尝试添加curl跟随302重定向
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
还要确保您的http_build_query()函数使用“&amp;”作为参数分隔符。在某些PHP配置上,它可能是“&amp; amp;”默认情况下
$query = http_build_query($data, '', '&');
答案 2 :(得分:0)
仅curl_setopt($ch,CURLOPT_POSTFIELDS, $curl_parameters);
怎么样?我认为您不需要致电http_build_query
。