file_get_contents无法从正确的url中检索html

时间:2018-05-20 13:32:24

标签: php

我正试图通过此api调用获取响应json。为此,我按以下方式构建URL:

$currentDate = date("Y-m-d");
$timestamp = date("Y-m-d H:m:s");

$url =  "https://int.soccerway.com/a/block_home_matches?block_id=block_home_matches_30&callback_params=";
$url .= "{\"block_service_id\":\"home_index_block_homematches\",\"date\":\"". $currentDate ."\",";
$url .= "\"display\":\"now_playing\",\"timestamp\":\"". $timestamp . "\"}";
$url .= "&action=filterContent&params=";
$url .= "{\"display\":\"now_playing\"}";

所以我执行了请求:

$html = file_get_contents($url);
$json = json_decode($html);

我明白了:

  

无法打开流:HTTP请求失败!找不到HTTP / 1.0 404

但链接是正确的,事实上,如果您粘贴$url,则可以看到正确的回复。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

网址只编码不是网址参数的值。 e.g。

$currentDate = date("Y-m-d");
$timestamp = date("Y-m-d H:m:s");

$url =  'https://int.soccerway.com/a/block_home_matches?block_id=block_home_matches_30&callback_params=';
$url .= urlencode('{"block_service_id":"home_index_block_homematches","date":"'. $currentDate . '","display":"now_playing","timestamp":"' . $timestamp . '"}');
$url .= '&action=filterContent&params=';
$url .= urlencode('{"display":"now_playing"}');

使用单引号进行封装也更容易一些,我将来会使用json_encode来构建JSON字符串。

json_encode示例为:

$url =  'https://int.soccerway.com/a/block_home_matches?block_id=block_home_matches_30&callback_params=';
$json['block_service_id'] = 'home_index_block_homematches';
$json['date'] = date("Y-m-d");
$json['display'] = 'now_playing';
$json['timestamp'] = date("Y-m-d H:m:s");
$url .= urlencode(json_encode($json));
$url .= '&action=filterContent&params=';
$url .= urlencode(json_encode(array('display' => 'now_playing')));