Google API - URL Shortener with PHP

后端 未结 8 2034
爱一瞬间的悲伤
爱一瞬间的悲伤 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 12:53

    $longUrl = "http://www.xxxxxxx.com";
        $postData = array('longUrl' => $longUrl);
        $jsonData = json_encode($postData);
    
        //4
        $curlObj = curl_init(); 
        curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?key=yourappkey');
        curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curlObj, CURLOPT_HEADER, 0);
        curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt($curlObj, CURLOPT_POST, 1);
        curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
    
        //5
        $response = curl_exec($curlObj);
    
        $json = json_decode($response);
    //       echo "
    ";
    //    print_r($json);exit;
        //6
        curl_close($curlObj);
    
        //7
        if(isset($json->error)){
            echo $json->error->message;
        }else{
            echo $json->id;
        }   
    

提交回复
热议问题