Google API - 使用PHP的URL Shortener

Its*_*ner 20 php url curl qr-code

我的代码如下.URL缩短服务有效,但是当我插入我的时,它不会$POST.有谁知道如何修复这个我看代码?

// This is the URL you want to shorten
$longUrl = 'http://www.mysite.com/XXXXX/XX/$_POST['qrname']';

// Get API key from : http://code.google.com/apis/console/
$apiKey = 'MyAPIKey';

$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);

$curlObj = curl_init();

curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
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);

$response = curl_exec($curlObj);

// Change the response json string to object
$json = json_decode($response);

curl_close($curlObj);

echo 'Shortened URL is: '.$json->id;
Run Code Online (Sandbox Code Playgroud)

Hac*_*web 11

请尝试以下方式

$longUrl = 'http://www.mysite.com/XXXXX/XX/'.$_POST['qrname'];

以上将有效.

  • 您的问题与cURL无关,它是关于在PHP中连接变量和字符串,请参阅http://php.net/manual/de/language.types.string.php (8认同)

deb*_*ish 7

$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 "<pre>";
//    print_r($json);exit;
    //6
    curl_close($curlObj);

    //7
    if(isset($json->error)){
        echo $json->error->message;
    }else{
        echo $json->id;
    }   
Run Code Online (Sandbox Code Playgroud)


Mah*_*ary 6

你在单引号之间传递php变量,所以它不会被解析.在双引号之间传递它

$longUrl = "http://www.mysite.com/XXXXX/XX/$_POST['qrname']";
Run Code Online (Sandbox Code Playgroud)

或者像这样结合

$longUrl = 'http://www.mysite.com/XXXXX/XX/'.$_POST['qrname'];
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这个答案而不是Hackableweb,因为它不仅解决问题,而且还告诉OP,***为什么***! (2认同)

urs*_*acv 6

你有一把钥匙,但你没有正确使用它

您应该将其附加到网址,不要在帖子中发送密钥

https://www.googleapis.com/urlshortener/v1/url?key='.$apiKey
Run Code Online (Sandbox Code Playgroud)

请访问https://developers.google.com/url-shortener/v1/url/insert

  • 这解决了它,一些现有的文档已经过时了. (4认同)