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

报告相同问题?

悬赏问题

  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码