2016-02-04 89 views
1

我试图通过谷歌的距离矩阵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']; 

?> 
+0

您使用的是单引号,但似乎在字符串中有php变量 - 它们需要在整个url周围没有引号/转义或使用双引号。即:'$ URL =“http://maps.googleapis.com/maps/api/distancematrix/json?origins={$value}&destinations={$value2}&mode=driving&language=English- EN&关键= {$键} “' – RamRaider

+0

和JSON后'有空格'在上述网址 – RamRaider

+0

@RamRaider嘿谢谢!现在它工作得很好。继续,把它扔进一个帖子,所以我可以将它标记为答案 – jameson1128

回答

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}"; 
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']; 

?>