簡體   English   中英

Google Translate API 中的多個輸入(q 參數),帶有 PHP CURL

[英]Multiple input (q parameters) in Google Translate API , with PHP CURL

當我們查詢 [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']   ) );

您應該對發布字段進行編碼。 PHP提供了http_build_query

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, http_build_query($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'=> array("hello", "world"), 'source'=>"en", 'target'=>'ru']   ) );

相關的是這個帖子這個帖子

正如評論中所建議的那樣,您可以為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"
      }
    ]
  }
}

對於其他人在這里找到自己的方式並尋找如何將簡單的 GET 請求中的多個文本翻譯到Google Cloud Translation v2 REST API ,您只需將多個q=參數添加到您的 URL 中。

無需處理 cURL,只需使用file_get_contents並繼續您的生活。 像這樣的事情可以完成這項工作:

$texts = ['foo', 'bar', 'hello world'];

// Translate from english to swedish
$queryParams = [
    'target' => 'sv',
    'source' => 'en',
    'format' => 'text',
    'key'    => 'INSERT_YOUR_API_KEY_HERE',
];

// Now let's add q=<text> for each text
$queryString = http_build_query($queryParams);
foreach($texts as $t){
    $queryString .= '&q='.rawurlencode($t);
}

$url = "https://translation.googleapis.com/language/translate/v2?$queryString";

$responseBody = file_get_contents($url);
$responseArr = json_decode($responseBody, true);

你應該使用 q 參數作為 json_encode(array($text1,$text2))

這是我工作良好的代碼片段。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://translation.googleapis.com/language/translate/v2?API-KEY');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$text1="The Great Pyramid of Giza (also known as the Pyramid of Khufu or the Pyramid of Cheops) is the oldest and largest of the three pyramids in the Giza pyramid complex.";
$text2="this is second text example";
$post = array(
    'q'=> json_encode(array($text1,$text2)),
    'source'=>"en",
    'target'=> "sr",//serbian sr
    'format'=>"text",   
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$result=json_decode($response,true);
print_r($result['data']['translations']);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM