0

I am trying to use google trnslation apis to translate some texts from English to Dutch. I have the following code:-

$text = urlencode($text);
$from_lan = 'en';
$to_lan = 'nl';
$url = "https://translate.googleapis.com/translate_a/single?client=p&sl=".$from_lan."&tl=".$to_lan."&dt=t&q=".$text;
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
print_r($content);

The data which I am getting is:-

[[["uitzicht","view",,,2]],,"en"] 

It is not array or json data. It is string. How can I get data in json format

Saswat
  • 12,320
  • 16
  • 77
  • 156

2 Answers2

0

Remove the duplicate comma's using a regex. Then encode/parse to json. This works in js, but not tested in php.

Here's js/jquery versions for comparison:

// error
$.ajax({
    url: "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=nl&dt=t&q=view",
    dataType: "text"
  })
  .done(function(data) {
    console.log(JSON.parse(data)[0][0][0]);
  });

// works (replaces duplicate comma's with single ones)
$.ajax({
    url: "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=nl&dt=t&q=view",
    dataType: "text"
  })
  .done(function(data) {
    console.log(JSON.parse(data.replace(/,+/g, ","))[0][0][0]);
  });
yezzz
  • 2,990
  • 1
  • 10
  • 19
0

Use Json Decode (Takes a JSON encoded string and converts it into a PHP variable)

var_dump(json_decode($content)); //Output is object variable
var_dump(json_decode($content, true)); //Output is array variable
Faraona
  • 1,685
  • 2
  • 22
  • 33