php file_get_contents和& amp; [英] php file_get_contents and &

查看:374
本文介绍了php file_get_contents和& amp;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use php's file_get_content('a url');

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

The thing is if the url has '&' in it, for example

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

它会自动向www.google.com/?var1=1&var2=2

如何防止这种情况发生?

How do I prevent that from happening?

推荐答案

我同意该问题的原始发帖人.具体来说:

I agree with the original poster of the question. To be very specific:

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不喜欢我:

This requires the sensor=false variable to be passed, or the query will return BAD results from Google. If I pass this STRING through file_get_contents, it (PHP file_get_contents) replaces the "&" with "&" so Google doesn't like me:

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
)

这是我使用http_build_query

So this is the solution I came up with, using 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()));

我还包括在 PHP网站为PHP使用自定义功能< 5:

I also include the code (thanks Marco K.) I found on the PHP website to use a custom function for 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

这篇关于php file_get_contents和&amp; amp;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆