php curl帮助google url shortener api

时间:2011-01-14 05:15:37

标签: php json curl

我试图使用谷歌apis缩短网址。这是我的PHP代码。当我加载时它给出一个空白页

<?php
    define('GOOGLE_API_KEY', 'GoogleApiKey');
    define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');

    function shortenUrl($longUrl)
    {
        // initialize the cURL connection
        $ch = curl_init(
            sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
        );

        // tell cURL to return the data rather than outputting it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // create the data to be encoded into JSON
        $requestData = array(
            'longUrl' => $longUrl
        );

        // change the request type to POST
        curl_setopt($ch, CURLOPT_POST, true);

        // set the form content type for JSON data
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

        // set the post body to encoded JSON data
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));

        // perform the request
        $result = curl_exec($ch);
        curl_close($ch);

        // decode and return the JSON response
        return json_decode($result, true);
    }
    if (isset($_POST['url'])) {  
    $url = $_POST['url'];
    $response = shortenUrl('$url');

    echo sprintf(
        $response['longUrl'],
        $response['id']
     );
 }
?>

我的html文件:

<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>

<FORM NAME ="form1" METHOD =" " ACTION = "shortner.php">

<INPUT TYPE = "TEXT" VALUE ="Enter a url to shorten" name="url">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Shorten">

</FORM>
</body>
</html

5 个答案:

答案 0 :(得分:5)

我想我找到了解决问题的方法。由于您要连接到使用SSL的URL,因此您需要在代码中为CURL添加一些额外的参数。请尝试以下方法:

<?php
    define('GOOGLE_API_KEY', 'GoogleApiKey');
    define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');

    function shortenUrl($longUrl)
    {
        // initialize the cURL connection
        $ch = curl_init(
            sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
        );

        // tell cURL to return the data rather than outputting it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // create the data to be encoded into JSON
        $requestData = array(
            'longUrl' => $longUrl
        );

        // change the request type to POST
        curl_setopt($ch, CURLOPT_POST, true);

        // set the form content type for JSON data
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

        // set the post body to encoded JSON data
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));

        // extra parameters for working with SSL URL's; eypeon (stackoverflow)
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // perform the request
        $result = curl_exec($ch);
        curl_close($ch);

        // decode and return the JSON response
        return json_decode($result, true);
    }
    if (isset($_POST['url'])) {  
    $url = $_POST['url'];
    $response = shortenUrl('$url');

    echo sprintf(
        $response['longUrl'],
        $response['id']
     );
 }
?>

答案 1 :(得分:1)

如果某些内容与请求不符,

curl_exec()会返回布尔值false。你没有测试它并假设它有效。将您的代码更改为:

$result = curl_exec($ch);

if ($result === FALSE) {
    die("Curl error: " . curl_error($ch);
}

同样,您需要指定CURLOPT_RETURNTRANSFER - 默认情况下,curl会将收到的任何内容写入PHP输出。设置此选项后,它会将传输返回到$ result变量,而不是将其写出来。

答案 2 :(得分:1)

我认为它来自你的HTML。你没有放置表格方法,所以它通过get发送数据。

只有在你发帖的时候才能表现出来。

尝试使用表单method =“post”


修改

鲍比的主要问题是你在这段代码中没有一个问题,只有几个问题。 首先,如果你不这样做

<FORM NAME="form1" METHOD="POST" ACTION="shortner.php">

if (isset($_POST['url']))将永远不会返回true,因为表单发送的变量将是GET(或执行if (isset($_GET['url'])))。

其次,您使用{ $response = shortenUrl('$url'); }.调用该函数。此处您不是发送url值而是发送字符串'$ url'。所以你的变量$ longUrl总是'$ url'。

第三,你不要像你应该那样使用sprintf。

echo sprintf(
        $response['longUrl'],
        $response['id']
     );

Sprintf需要采用字符串格式:

echo sprintf("%s %s" // for example
    $response['longUrl'],
    $response['id']
 );

但是你知道你可以直接做吗

echo $response['longUrl'] . ' ' . $response['id'];

您可以直接连接字符串。在PHP

答案 3 :(得分:0)

您需要在代码中设置CURLOPT_RETURNTRANSFER选项

function shortenUrl($longUrl)
    {
        // initialize the cURL connection
        $ch = curl_init(
            sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
        );

        // tell cURL to return the data rather than outputting it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // create the data to be encoded into JSON
        $requestData = array(
            'longUrl' => $longUrl
        );

        // change the request type to POST
        curl_setopt($ch, CURLOPT_POST, true);

        // set the form content type for JSON data
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));


        // set the post body to encoded JSON data
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));


        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);


        // perform the request
        $result = curl_exec($ch);
        curl_close($ch);

        // decode and return the JSON response
        return json_decode($result, true);
    }
    if (isset($_POST['url'])) {  
    $url = $_POST['url'];
    $response = shortenUrl('$url');

    echo sprintf(
        $response['longUrl'],
        $response['id']
     );
 }

答案 4 :(得分:-1)

// Create cURL
$apiURL = https://www.googleapis.com/urlshortener/v1/url?key=gfskdgsd
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
    curl_setopt($ch,CURLOPT_URL,$apiURL);
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
    curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
    curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);