Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google Translate API中的多个输入(q参数),带有PHP CURL_Php_Curl_Google Cloud Platform_Google Translate_Google Translation Api - Fatal编程技术网

Google Translate API中的多个输入(q参数),带有PHP CURL

Google Translate API中的多个输入(q参数),带有PHP CURL,php,curl,google-cloud-platform,google-translate,google-translation-api,Php,Curl,Google Cloud Platform,Google Translate,Google Translation Api,当我们对[Translate API][1]进行查询时: function curl($url, $post_array=false){ $handle = curl_init(); if (FALSE === $handle) throw new Exception('failed to CURL initialize; '. __FILE__); curl_setopt($handle, CURLOPT_URL, $

当我们对[Translate API][1]进行查询时:

function curl($url, $post_array=false){ 
        $handle = curl_init();
        if (FALSE === $handle) 
            throw new Exception('failed to CURL initialize; '. __FILE__);
        curl_setopt($handle, CURLOPT_URL, $url);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
        if($post_array) {
            curl_setopt($handle, CURLOPT_POST, 1 );
            curl_setopt($handle, CURLOPT_POSTFIELDS, $post_array );
        } 
        curl_setopt($handle,CURLOPT_HTTPHEADER,array('X-HTTP-Method-Override: GET'));
        $response = curl_exec($handle);
        return $response;
}


var_dump ( curl("https://www.googleapis.com/language/translate/v2", ['key'=>$key, 'q[]'=>"hello", 'q[]'=>"world", 'source'=>"en", 'target'=>'ru']   ) );
以错误结尾:

{
  "error": {
    "code": 400,
    "message": "Required Text",
    "errors": [
      {
        "message": "Required Text",
        "domain": "global",
        "reason": "required"
      }
    ]
  }
}

如何发送多个
q
输入文本?如我所见,API不允许
q[]
类型数组,而是使用多个
q
参数。但是在
php
中,我们不能在数组中多次使用相同的键…

我相信这个API支持JSON,JSON支持数组,所以就这样做吧

function curl($url, array $post_array){ 
        $handle = curl_init();
        curl_setopt_array($ch,array(
CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>json_encode($post_data),
CURLOPT_HTTPHEADER=>array('Content-Type: application/json')
));
(...)
}
就这样说吧

var_dump ( curl("https://www.googleapis.com/language/translate/v2",
 ['key'=>$key, 'q'=>array("hello","world"),
 'source'=>"en", 'target'=>'ru']   ) );

您应该对post字段进行编码。PHP提供了http\u build\u查询

函数curl($url,$post_array=false){
$handle=curl_init();
if(FALSE==$handle)
抛出新异常('未能卷曲初始化;'。\u文件\u);
curl_setopt($handle,CURLOPT_URL,$URL);
curl_setopt($handle,CURLOPT_RETURNTRANSFER,1);
curl_setopt($handle,CURLOPT_SSL_VERIFYPEER,false);
if($post_数组){
卷曲设置($handle,CURLOPT_POST,1);
curl_setopt($handle,CURLOPT_POSTFIELDS,http_build_query($post_array));
} 
curl_setopt($handle,CURLOPT_HTTPHEADER,array('X-HTTP-Method-Override:GET');
$response=curl\u exec($handle);
返回$response;
}
变量转储(卷曲)https://www.googleapis.com/language/translate/v2“,['key'=>$key,'q'=>array(“hello”,“world”),'source'=>en','target'=>ru']);

相关的是和。

如注释中所建议的,而不是使用在POSTFIELDS数据数组(或PHP中的任何数组)中不能重复键的数组,您可以为POST数据提供字符串

我的旋度函数

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;
}

文档
https://cloud.google.com/translate/docs/reference/translate
建议参数只是
q
而不是
q[]
,您应该根据需要重复多次。@RamRaider但是php不允许在数组中使用多个相同的键使用字符串而不是数组作为
postfields
$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"
      }
    ]
  }
}