Google API - URL Shortener with PHP

后端 未结 8 2031
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 12:24

My code is below. The URL shortening service works, but it doesn\'t when I insert my $POST. Does anyone know how to fix this my looking at the code?



        
8条回答
  •  遇见更好的自我
    2021-02-02 13:00

    Try with this code. I is working for me.

    $api_key = 'YOUR_KEY';
    $request_data = array(
        'longUrl' => 'YOUR_LONG_URL'
    );
    
    $curl_obj = curl_init(sprintf('%s/url?key=%s', 'https://www.googleapis.com/urlshortener/v1', $api_key));
    curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_obj, CURLOPT_POST, true);
    curl_setopt($curl_obj, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($curl_obj, CURLOPT_POSTFIELDS, json_encode($request_data));
    curl_setopt($curl_obj, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl_obj, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($curl_obj);
    $json = json_decode($response);
    curl_close($curl_obj);
    
    var_dump($json);
    die();
    

提交回复
热议问题