douchen4534 2018-05-20 13:32
浏览 65
已采纳

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

I'm trying to get the response json from this api call. For doing this I build the url in the following way:

$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\"}";

so I executed the request:

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

I get:

failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found

but the link is correct, infact if you paste the $url you can see the correct response.

What I did wrong?

  • 写回答

1条回答 默认 最新

  • duanjianl183188 2018-05-20 13:46
    关注

    URL encode just the values that aren't URL parameters. 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"}');
    

    It also is a bit easier to use single quotes for the encapsulation, and I would use json_encode to build JSON strings in the future.

    A json_encode example would be:

    $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')));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图