【发布时间】:2014-01-21 15:18:22
【问题描述】:
我正在为我大学的编程课程做一个小项目。它涉及从 google 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.
【问题讨论】:
-
@MarcB 他已经是了,检查他的代码。此外,他甚至提到存储在
$url中的 url 在粘贴到浏览器时可以工作...... -
是的,抱歉,完全错过了......这里是伪星期一的乐趣。
-
您能否提供一个 Curl 正在尝试的已完成 URL 的示例。
-
上面代码中的url如下:maps.googleapis.com/maps/api/directions/json?origin=H.J.E。 Wenckebachweg 2550,Amsterdam&destination=Damrak 36,Amsterdam&sensor=false&mode=bicycling 当我添加 '$url = urlencode($url);'在 $url 和 echo 之间它变成: http%3A%2F%2Fmaps.googleapis.com%2Fmaps%2Fapi%2Fdirections%2Fjson%3Forigin%3DH.J.E.+Wenckebachweg+2550%2C+Amsterdam%26destination%3DDamrak+36%2C+阿姆斯特丹%26sensor%3Dfalse%26mode%3Dbicycling
-
是的,我的错。只是变量需要像我修改后的答案一样编码。
标签: php json google-maps curl var-dump