我正在尝试使用php的file_get_content('a url');
例如,如果网址中包含"&",那就是问题
file_get_contents('http://www.google.com/?var1=1&var2=2')
它会自动发出请求 www.google.com/?var1=1&var2=2
我该如何防止这种情况发生?
我同意问题的原始海报.非常具体:
这需要传递sensor = false变量,否则查询将从Google返回BAD结果.如果我通过file_get_contents传递此STRING,它(PHP file_get_contents)会替换"&","&"
因此Google不喜欢我:
Array
(
[type] => 2
[message] => file_get_contents(http://maps.googleapis.com/maps/api/geocode/json?address=301 E. Linwood Avenue Turlock, CA&sensor=false) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
)
Run Code Online (Sandbox Code Playgroud)
所以这是我提出的解决方案,使用http_build_query
$myURL = 'http://maps.googleapis.com/maps/api/geocode/json?';
$options = array("address"=>$myAddress,"sensor"=>"false");
$myURL .= http_build_query($options,'','&');
$myData = file_get_contents($myURL) or die(print_r(error_get_last()));
Run Code Online (Sandbox Code Playgroud)
我还包括我在PHP网站上找到的代码(感谢Marco K.)使用PHP <5的自定义函数:
if (!function_exists('http_build_query')) {
function http_build_query($data, $prefix='', $sep='', $key='') {
$ret = array();
foreach ((array)$data as $k => $v) {
if (is_int($k) && $prefix != null) {
$k = urlencode($prefix . $k);
}
if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
if (is_array($v) || is_object($v)) {
array_push($ret, http_build_query($v, '', $sep, $k));
} else {
array_push($ret, $k.'='.urlencode($v));
}
}
if (empty($sep)) $sep = ini_get('arg_separator.output');
return implode($sep, $ret);
}// http_build_query
}//if
Run Code Online (Sandbox Code Playgroud)
您应该尝试查看 PHP 中的 CURL 库,它允许您执行以下操作:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://mysite.com/file.php?blah=yar&test=blah");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)
然后您可以从 $data 获取结果。