1

I am trying to pass some html form input through google distance matrix api. I have put them into variables and replaced the spaces with "+" signs. When I echo the variables they are perfect. When I hard code those variable values the api returns the distance, but it returns nothing when I use the variable representations.

<?php

$start = $_POST["origin"];
$end = $_POST["destination"];


$value = strtolower(str_replace(' ', '+', $start));

echo $value;

$value2 = strtolower(str_replace(' ', '+', $end));

echo $value2;

$url = 'http://maps.googleapis.com/maps/api/distancematrix/json?   
origins=$value&destinations=$value2&mode=driving&language=English- 
en&key=$key"';
$json = file_get_contents($url); // get the data from Google Maps API
$result = json_decode($json, true); // convert it from JSON to php array
echo $result['rows'][0]['elements'][0]['distance']['text'];

?>
4

2 回答 2

1

问题在于处理 PHP 变量时单引号的使用/误用。如果您使用单引号,则其中的变量必须不加引号/转义,以便正确解释它们。也许更有利的方法是在整个字符串/ url 周围使用双引号 - 如有必要,使用花括号以确保正确处理某些类型的变量(即:使用数组变量{$arr['var']}

对于上述情况,以下应该可以工作 - 故意显示在一行上以突出显示 url 中现在没有空格。

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins={$value}&destin‌​ations={$value2}&mode=driving&language=English-en&key={$key}";
于 2016-02-04T23:16:43.113 回答
0

您的 $url 变量是使用文字引号(单引号)设置的。

如果要在字符串中使用变量,则需要使用双引号,否则需要连接。

我还看到一个额外的双引号挂在您的 url 字符串的末尾,请尝试更正:

<?php

$start = urlencode($_POST["origin"]);
$end = urlencode($_POST["destination"]);

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?   
origins={$start}&destinations={$end}&mode=driving&language=English- 
en&key=$key";

$json = file_get_contents($url); // get the data from Google Maps API
$result = json_decode($json, true); // convert it from JSON to php array

echo $result['rows'][0]['elements'][0]['distance']['text'];

?>
于 2016-02-04T23:14:15.263 回答