使用CURL和PHP进行POST请求无法正常工作

4
我正在尝试使用位于http://nlp.stanford.edu:8080/corenlp/process的表单以编程方式处理我的语句。 我在PHP / CURL中有以下代码片段。 然而,它没有处理该语句,而是返回表单的HTML - 就好像没有发送POST参数一样。 我已检查我是否发送了必需的参数。 有人能指导我我错在哪里吗?
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://nlp.stanford.edu:8080/corenlp/process");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/14.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, true);

$data  = array(
    'outputFormat' => 'xml',
    'input' => 'Here is a statement to process',
    'Process' => 'Submit Query'
     );

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$result = curl_exec($ch);
echo $result;

1
你复制了关于那个表单的所有东西吗?包括 cookies、referer、反垃圾邮件隐藏字段等等...? - Marc B
提交按钮未标记为“提交查询”。 - mario
页面中有一些cookie,请尝试将其包含在内。 - Oussama Jilal
我该如何添加cookies、引荐等内容?很抱歉,我对CURL/PHP不熟悉。 - user2109015
它返回的是该网站的表单,而不是输出结果。当我手动提交表单时,它可以正常工作。 - user2109015
显示剩余4条评论
1个回答

0

你需要将 $data 数组转换为字符串... 同时,确保对每个值进行 urlencode()

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://nlp.stanford.edu:8080/corenlp/process");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/14.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, true);

$data  = array(
"outputFormat" => "xml",
"input" => "Here is a statement to process",
"Process" => "Submit Query"
 );

$data_string = "";

foreach($data as $key=>$value){ /// YOU HAVE TO DO THIS
$data_string .= $key.'='.urlencode($value).'&';  /// AND THIS
}

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
echo $result;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接