Search code examples
phpfile-get-contents

Variables not working inside file_get_contents php


Im trying to pull content from google maps API. But when I concatenate a variable inside the URL it doesn't work If I just use the plan text it works. What am i doing wrong here?

Not working:

$post_location = "lagos";
$url_loc = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $post_location .'&sensor=true&key=AIzaSyDXX_Y0-7b1XM2';
$obj = json_decode(file_get_contents($url_loc), true);

var_dump($obj); //outputs null

But this works:

$url_loc = 'https://maps.googleapis.com/maps/api/geocode/json?address=lagos&sensor=true&key=AIzaSyDXX_Y0-7b1XM2';
$obj = json_decode(file_get_contents($url_loc), true);

var_dump($obj); //outputs all results

Why isnt the first option working?

Full code i'm working with

<form action="" method="POST">
<input type="text" name="surl" value="/storefront/output.json">
<input type="submit" value="Submit"/>
</form>

if ($_SERVER['REQUEST_METHOD'] == 'POST'){  

  $url = $_POST['surl'];
  $string = file_get_contents($url);
  $json_a = json_decode($string, true);
  $post_id = 243;

  foreach ($json_a as $person_name => $person_a) {

        $post_location =  $person_a['location'];
        $url_loc = 'https://maps.googleapis.com/maps/api/geocode/json?address='.$post_location.'&sensor=true&key=AIzaSyDXX_Y0-7b1XM2';
        $obj = json_decode(file_get_contents($url_loc), true);
        var_dump($obj); // outputs null

        foreach ($obj as $key ) {     

                $lat = $key[0]['geometry']['location']['lat'];
                $lng = $key[0]['geometry']['location']['lng'];


                $full_address = $key[0]['formatted_address'];

                update_post_meta( $post_id, 'prod-lat', sanitize_text_field( $lat )); 
                    update_post_meta( $post_id, 'prod-lng', sanitize_text_field( $lng )); 



            break;

        } 
  }

}

Solution

  • I thing you're passing illegal characters to URL string. If you want to pass your $post_location variable to URL use urlencode function:

    $post_location = "some address here";
    $url_loc = 'https://maps.googleapis.com/maps/api/geocode/json?address='. 
    urlencode($post_location) .'&sensor=true&key=AIzaSyDXX_Y0-7b1XM2';
    $obj = json_decode(file_get_contents($url_loc), true);
    

    Without urlencode you'll get warning: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /var/www/public_html/index.php on line 7 - look into your log files or display all PHP errors.