变量在 php file_get_contents不起作用



我试图从谷歌地图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;
} 
}
}

我认为您正在将非法字符传递给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- 查看您的日志文件或显示所有 PHP 错误。

相关内容

  • 没有找到相关文章

最新更新