PHP - 在函数参数中获取URL

时间:2012-12-07 11:51:24

标签: php function

当我手动将URL字符串放在参数中时,我有以下功能。我需要它是动态的,我正在使用Wordpress。

    function get_tweets($url) {     
$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' .  $url);
$json = json_decode($json_string, true);
return intval( $json['count'] );
}
// Below is the one that works manually     
<?php echo get_tweets('http://www.someurl.com');

//ones I have tried that do not (trying to make dynamic)
$url = $get_permalink();

echo get_tweets('$url');
echo get_tweets($url);

$url = '$get_permalink()'; 
$url = $get_permalink(); // produces needs to be in string error
echo get_tweets($url);

3 个答案:

答案 0 :(得分:0)

你所做的事情本身并没有错。我能看到的唯一明显的错误是你没有正确编码URL。您需要确保您在URL中放置的查询字符串参数已正确进行URL编码,否则远程主机可能无法正确解释请求。

function get_tweets($url) {     
    $json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' .  urlencode($url));
    $json = json_decode($json_string, true);
    return intval( $json['count'] );
}

echo get_tweets('http://www.someurl.com'); // should work just fine

答案 1 :(得分:0)

您是否尝试urlencode您的网址字符串?

urlencode($foo);

答案 2 :(得分:0)

您的主要问题在下面

更改

//ones I have tried that do not (trying to make dynamic)
$url = $get_permalink();

//ones I have tried that do not (trying to make dynamic)
$url = get_permalink();