调用IBM Watson NLU接口:PHP中CURL POST报400错误但CLI正常
解决IBM Watson NLU PHP请求400错误的问题
你的PHP代码存在两个关键问题,导致返回400 Bad Request错误:
- POST数据格式不匹配:当给
CURLOPT_POSTFIELDS传入数组时,PHP cURL会自动将数据编码为application/x-www-form-urlencoded格式,但Watson NLU API要求接收application/json格式的请求体,必须先将数组转为JSON字符串再传入。 - 参数类型错误:
emotion字段需要的是布尔值true,而你代码中写的是字符串'true',API无法识别该类型的参数。
修正后的PHP代码如下:
<?php /* API URL */ $apikey = '***my-api-key***'; $url = 'https://api.au-syd.natural-language-understanding.watson.cloud.ibm.com/instances/0623bfb1-a19a-456b-b3df-12a42434241de/v1/analyze?version=2019-07-12'; /* Init cURL resource */ $ch = curl_init($url); /* Array Parameter Data - 修正布尔值类型 */ $data = array( 'text' => 'I love apples! I do not like oranges.', 'features' => array( 'keywords' => array('emotion' => true) ) ); /* 将数组编码为JSON字符串后传入POST字段 */ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); /* set the content type json */ $headers = []; $headers[] = 'Content-Type:application/json'; curl_setopt($ch, CURLOPT_USERPWD, 'apikey:' . $apikey); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); /* set return type json */ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); /* execute request */ $result = curl_exec($ch); // 若仍有问题,可先打印原始响应排查具体错误 // echo $result; /* close cURL resource */ $response = json_decode($result); print_r($response); curl_close($ch); ?>
补充说明:
- 用
json_encode($data)将数组转为标准JSON字符串,确保请求体格式与CLI命令完全一致。 - 将
'true'改为true,保证参数类型符合API要求,让服务端能正确解析布尔值参数。
内容的提问来源于stack exchange,提问作者Tanvir Nabil
相关产品推荐
相关产品推荐

