为什么谷歌距离矩阵不接受我的变量作为位置


Why is google distance matrix not accepting my variables as locations?

我正在尝试通过谷歌距离矩阵API传递一些html表单输入。我将它们放入变量中并用"+"号替换空格。当我回显变量时,它们是完美的。当我对这些变量值进行硬编码时,api 返回距离,但在使用变量表示时它不返回任何内容。

<?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'];
?>

问题在于使用 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}";

您的$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'];
?>