变量在file_get_contents php内部不起作用

时间:2018-08-17 18:52:28

标签: php file-get-contents

我正在尝试从Google Maps API中提取内容。 但是当我在URL中连接变量时,它不起作用 如果我只使用计划文本,则可以使用。 我在这里做什么错了?

不起作用:

$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

但这可行:

$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

为什么第一个选项不起作用?

我正在使用的完整代码

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

        } 
  }

}

1 个答案:

答案 0 :(得分:1)

我要向URL字符串传递非法字符。如果要将$ post_location变量传递给URL,请使用urlencode函数:

$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);

没有urlencode,您将得到警告:failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /var/www/public_html/index.php on line 7-查看日志文件或打开错误显示