php file_get_contents和&

Pat*_*ick 23 php

我正在尝试使用php的file_get_content('a url');

例如,如果网址中包含"&",那就是问题

file_get_contents('http://www.google.com/?var1=1&var2=2')

它会自动发出请求 www.google.com/?var1=1&var2=2

我该如何防止这种情况发生?

msh*_*fer 8

我同意问题的原始海报.非常具体:

http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=301+E.+Linwood+Avenue++Turlock%2C+CA

这需要传递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&amp;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)


Mit*_*sey 3

您应该尝试查看 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 获取结果。

  • 如果 file_get_contents 应该正常工作,为什么要使用 cURL(用户可能没有在他们的 PHP 安装中安装它,因为它是一个额外的扩展)?在这种情况下,URL 编码看起来似乎发生了一些奇怪的事情。 (2认同)
  • 我不同意 file_get_contents 不是为 URL 设计的。检查 www.php.net 上的函数手册,您会发现第一个示例实际上演示了通过 HTTP 读取文件。但我同意它的目的以最简单的 GET 请求结束。不支持任何更复杂的操作(POST、操作标头、上传文件等)。但是,我不建议使用 cURL,因为它是相当旧的扩展。相反,如何查看 Zend_Http,它是 Zend Framework 的一部分并且完全面向对象:http://framework.zend.com/manual/en/zend.http.client.html (2认同)