正如评论中所建议的那样,您可以为 POST 数据提供字符串,而不是使用 POSTFIELDS 数据数组(或 PHP 中的任何数组)中不能重复键的数组
我的卷曲功能
function curl( $url=NULL, $options=NULL ){
$cacert='c:/wwwroot/cacert.pem'; #<---- edit to suit
$vbh = fopen('php://temp', 'w+');
$res=array(
'response' => NULL,
'info' => array( 'http_code' => 100 ),
'headers' => NULL,
'errors' => NULL
);
if( is_null( $url ) ) return (object)$res;
session_write_close();
/* Initialise curl request object */
$curl=curl_init();
if( parse_url( $url,PHP_URL_SCHEME )=='https' ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
}
/* Define standard options */
curl_setopt( $curl, CURLOPT_URL,trim( $url ) );
curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_FAILONERROR, true );
curl_setopt( $curl, CURLOPT_HEADER, false );
curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $curl, CURLOPT_ENCODING, '' );
curl_setopt( $curl, CURLOPT_VERBOSE, true );
curl_setopt( $curl, CURLOPT_NOPROGRESS, true );
curl_setopt( $curl, CURLOPT_STDERR, $vbh );
/* Assign runtime parameters as options */
if( isset( $options ) && is_array( $options ) ){
foreach( $options as $param => $value ) curl_setopt( $curl, $param, $value );
}
/* Execute the request and store responses */
$res=(object)array(
'response' => curl_exec( $curl ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
rewind( $vbh );
$res->verbose=stream_get_contents( $vbh );
fclose( $vbh );
curl_close( $curl );
return $res;
}
请求的配置:
$key='AIzaSyxxxxxxxxxxxxxxxxxxx9oIhY8Q8xxxxx';
$url='https://www.googleapis.com/language/translate/v2';
$arr=array( 'another', 'elephant', 'banana', 'woman' );
/* some translate parameters */
$params=array(
'target' => 'fr',
'format' => 'text',
'source' => 'en',
'model' => 'nmt'
);
/* the POST data */
$query=implode( '&', array(
sprintf( 'key=%s&q=%s',$key, implode( '&q=', $arr ) ), #query
urldecode( http_build_query( $params ) ) #google params
));
$config=array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $query
);
$res=curl( $url, $config );
if( $res->info->http_code==200 ){
printf('<pre>%s</pre>',print_r( $res->response,true ) );
}
似乎可以正常工作并返回:
{
"data": {
"translations": [
{
"translatedText": "un autre",
"model": "nmt"
},
{
"translatedText": "l'éléphant",
"model": "nmt"
},
{
"translatedText": "banane",
"model": "nmt"
},
{
"translatedText": "femme",
"model": "nmt"
}
]
}
}