0
 <?php
$curl = curl_init();
 curl_setopt_array($curl, array(
            CURLOPT_URL => "https://openapi.naver.com/v1/papago/n2mt",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "utf-8",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "source=en&target=ko&text=" . htmlspecialchars($_GET["text"]),
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded",
                "X-Naver-Client-Id: xxxxxx",
                "X-Naver-Client-Secret: xxxxxx"
            ),
        ));
 $response = curl_exec($curl);
 $err = curl_error($curl);

 curl_close($curl);

 if (!$err)
 {
      //var_dump($response);
      echo $response;
      //echo $response->result->translatedText;
 }
?>

Output:

{"message":{"@type":"response","@service":"naverservice.nmt.proxy","@version":"1.0.0","result":{"srcLangType":"en","tarLangType":"ko","translatedText":"안녕하십니까","engineType":"N2MT","pivot":null}}}

I want to get the value of translatedText.

Kyros Koh
  • 188
  • 2
  • 12

1 Answers1

1

If the result is a string, you can parse it using json_decode and then access the property you need like any other array.

/** Your request **/
$jsonResult = '{"message":{"@type":"response","@service":"naverservice.nmt.proxy","@version":"1.0.0","result":{"srcLangType":"en","tarLangType":"ko","translatedText":"안녕하십니까","engineType":"N2MT","pivot":null}}}'

$values = json_decode($jsonResult, true);

echo $values['message']['result']['translatedText'];

Please note that this code is untested.

Nicolas
  • 8,077
  • 4
  • 21
  • 51