php file_get_contents($url) & 变成 &

php file_get_contents($url) & turns into &

我正在尝试像这样向 coinbase api 发出请求

$url = "https://api.gdax.com/products/BTC-USD/candles?start=".date($format,$starting_date)."&end=".date($format,$ending_date)."&granularity=".$granularity;

然后我在 file_get_contents($url) 中传递它,但它给了我一个错误

file_get_contents(https://api.gdax.com/products/BTC-USD/candles?start=2015-05-07&end=2015-05-08&granularity=900): 无法打开流:HTTP 请求失败! HTTP/1.1 400 错误请求。

问题当然是当“&”变成“&”时。

您可以使用以下命令还原 htmlspecialchars:

htmlspecialchars_decode();

尝试像这样调用 file_get_contents

file_get_contents(htmlspecialchars_decode($url));

试试看:

$url = html_entity_decode($url);
file_get_contents($url);

详情请见html_entity_decode

已更新

尝试替换

& with & in url as below

$url = "https://api.gdax.com/products/BTC-USD/candles?start=".date($format,$starting_date)."&end=".date($format,$ending_date)."&granularity=".$granularity;

尝试将双引号替换为单引号。这是此处列出的最简单的答案:

php file_get_contents and &

第一个涉及更多,但可能是更安全的选择。

看来您需要定义一个用户代理。 试试这个;

$url = "https://api.gdax.com/products/BTC-USD/candles?start=2015-05-07&end=2015-05-08&granularity=900";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

var_dump($result);

如果你还坚持使用file_get_contents那么用user agent还是可以的;

$url = "https://api.gdax.com/products/BTC-USD/candles?start=2015-05-07&end=2015-05-08&granularity=900";

$options = array(
    "http"=>array(
        "header"=>"User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad
    )
);

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

有关详细信息,您可以查看 file_get_contents and stream_context_create(使用 headers)文档

发布这个是因为它最适合我。我知道这是一个老问题。

我发现在使用 http_build_query 构建查询时,& 号问题消失了。

例子

$url = 'https://example.url';

// http_build_query builds the query from an array
$query_array = array (
    'search' => $string,
    'from' => $from,
    'to' => $to,
    'format' => 'json'
);

$query = http_build_query($query_array);
$result = file_get_contents($url . '?' . $query);

编辑:刚刚看到@joshi 的回答(实际上跟在link 之后),那里使用了http_build_query。

当您发送的参数之一不是 urlencoded 时,就会发生这种情况。

当 php 发现格式错误的 url(例如:带有空格或其他 url 列入黑名单的字符)时,它 url 对完整请求进行编码。