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

?>
jameson1128
  • 135
  • 2
  • 13

2 Answers2

1

The issue lies in the use / misuse of single quotes when working with PHP variables. If you use single quotes then variables within must be unquoted / escaped so that they are interpreted correctly. Perhaps the more favourable approach is to use double quotes around the entire string/url - use curly braces if necessary to ensure certain types of variables are processed properly ( ie: using an array variable {$arr['var']} )

For the situation above the following ought to work - shown on one line deliberately to highlight that there are now no spaces in the url.

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins={$value}&destin‌​ations={$value2}&mode=driving&language=English-en&key={$key}";
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
0

Your $url variable is being set using literal quotes (single quotes).

If you want to use variables inside a string you need to use double quotes, otherwise you need to concatenate.

I also see an extra double quote hanging on the end of your url string as well, try this with corrections:

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

?>
Architect Nate
  • 674
  • 1
  • 6
  • 21