1

当我尝试解析我的地理编码链接时,由于 amp; 陈述。在我“json_decode”字符串之前,我有一个名为 www.something.com/something?bla=bla&sensor=true 的链接,但是当我将它作为参数发送到函数时,它的 & 字符被转换为&. 像这样的链接

http://maps.googleapis.com/maps/api/geocode/json?address=Bekirdere,%20%C4%B0zmir&sensor=true 

工作正常,但链接喜欢

http://maps.googleapis.com/maps/api/geocode/json?address=Bekkirdere,%20%C4%B0zmit&sensor=true 

没有给出任何结果。(&转换为&)

我怎样才能阻止它被转换?

我的解析器功能:

function get_url_contents($url) 
{
    $url = str_replace(' ', '%20', $url); 
    $crl = curl_init();
    $timeout = 5;
    curl_setopt ($crl, CURLOPT_URL,$url);
    curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
    $ret = curl_exec($crl);
    curl_close($crl);
    return $ret;
}

function __construct($url)
{
    $json = $this->get_url_contents($url);
    $this->_jsonArray = json_decode($json, true);
}
4

1 回答 1

0

PHP urlencode()函数比执行 str_replace 更好,您应该只对 URL 中作为 GET 值的部分进行编码;您不应该对整个 URL 进行编码,因为正如您所指出的,这也会对将变量彼此分开的 & 符号进行编码。

您需要像这样构建 URL:

$url = 'http://maps.googleapis.com/maps/api/geocode/json?address=';
$url .= urlencode('Bekirdere, Izmir');
$url .= '&sensor=true';

然后curl按上述方式拨打电话。

我已经测试了下面的测试脚本,它可以工作:

$url = 'http://maps.googleapis.com/maps/api/geocode/json?address=';
$url .= urlencode('Bekirdere, Izmir');
$url .= '&sensor=true';

$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$ret = curl_exec($crl);
curl_close($crl);

$returned_data = json_decode($ret, true);
var_dump($returned_data);

您需要将其放入您的代码结构或重构您的类以接收$address参数(例如,'Izmir, Turkey')而不是完整的 URL(就像现在一样)。这样,您就可以在构建完整的 URL 以传递给curl.

于 2012-11-05T00:23:42.913 回答