如何将url中的信息转换为变量


how to get information from url into variable

所以我正试图通过反向地理编码获得位置https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding所以我的问题是(因为我对php很陌生)如何将URL中的结果转换为参数(结果将是json编码的数据)

您可以使用函数file_get_contents从URL 获取数据

    $API_KEY ="XXXXXXX";
    $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=".$API_KEY;
    $data = @file_get_contents($url);
    $jsondata = json_decode($data,true);
    if(is_array($jsondata) && $jsondata['status'] == "OK")
    {
         echo '<pre>'; print_r($jsondata);echo '</pre>';
    }

要获取数据,我们使用PHP curl函数。

[php]

// jSON URL which should be requested
$json_url = ‘www.yourdomain.com';
$username = ‘your_username';  // authentication
$password = ‘your_password';  // authentication
// jSON String for request
$json_string = ‘[your json string here]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . “:” . $password,  // authentication
CURLOPT_HTTPHEADER => array(‘Content-type: application/json’) ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string

[/php]

结果将是一个jSON字符串。

通常情况下,您必须向jSON URL发送一个jSON字符串,然后您就会得到一个jSON字符串。要对数据进行编码,只需使用php-jSON函数即可。使用json_encode从PHP数组创建json字符串,并使用json_decode将json字符串转换为PHP数组。