我正在为我的大学编写一个关于编程课程的小项目。它涉及从谷歌api(JSON)获取数据并向用户提供一些信息。
function compare($city, $start, $destination)
{
// merge city with start and destination
$city_start = $start . ', ' . $city;
$city_destination = $destination . ', ' . $city;
// reject symbols that start with ^
if (preg_match("/^\^/", $city) OR preg_match("/^\^/", $start) OR preg_match("/^\^/", $destination))
{
return false;
}
// reject symbols that contain commas
if (preg_match("/,/", $city) OR preg_match("/,/", $start) OR preg_match("/,/", $city))
{
return false;
}
// determine url
$url = "http://maps.googleapis.com/maps/api/directions/json?origin=$city_start&destination=$city_destination&sensor=false&mode=bicycling";
echo $url;
// open connection to google maps
$curl_session = curl_init($url);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_HEADER, 0);
// get data from json output
$json = curl_exec($curl_session);
curl_close($curl_session);
var_dump($json);
}
上面的代码在var_dump返回400错误,其中$ city,$ start和$ destination分别开始地址,目的地地址和地址所在的城市。存储在$ url中的url工作正常,并在浏览器中输入时返回JSON输出。
谁能告诉我我做错了什么?
干杯,
d
答案 0 :(得分:1)
您可以尝试urlencode
变量:
$city_start = urlencode($start . ', ' . $city);
$city_destination = urlencode($destination . ', ' . $city);