phpgoogle-app-enginefile-get-contentsurl-shortenergoogle-url-shortener

Google URL Shortener not working using file_get_contents


I am trying to short url with google api my site is hosted on google app engine so i cant use CURL have to use file_get_contents

$link = 'http://wwww.example.com';

$data = array('longUrl' => $link, 'key' => $apiKey);
$data = http_build_query($data);

$context = [
  'http' => [
  'method' => 'post',
  'header'=>'Content-Type:application/json',
  'content' => $data
  ]
];

$context = stream_context_create($context);
$result = file_get_contents('https://www.googleapis.com/urlshortener/v1/url', false, $context);

$json = json_decode($result);
print_r($json);

Above code gives error

stdClass Object
(
    [error] => stdClass Object
        (
            [errors] => Array
                (
                    [0] => stdClass Object
                        (
                            [domain] => global
                            [reason] => parseError
                            [message] => Parse Error
                        )

                )

            [code] => 400
            [message] => Parse Error
        )

)

Please correct me where i am doing wrong :(


Solution

  • The API is expecting a JSON-encoded request body (see https://developers.google.com/url-shortener/v1/url#resource), so you should really use json_encode instead of http_build_query.