HTTP 请求失败! HTTP/1.0 尝试从 youtube 获取内容时出现 400 错误请求

HTTP request failed! HTTP/1.0 400 Bad Request when trying to get content from youtube

当我尝试从 YouTube 上获取超过一个词的内容时出现此错误。

Warning: file_get_contents(https://www.youtube.com/results?search_query=html begginer): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\xampp\htdocs\sites\mime\beta\default.php on line 5

我的代码:

<?php
    $address = $_GET['q'];
    $address = 'https://www.youtube.com/results?search_query=' . $address;

    $html = file_get_contents($address);
    echo $html;
?>

但是,如果我尝试仅使用一个词(例如:http://127.0.0.1/sites/mime/beta/default.php?q=html)从 YouTube 获取内容,脚本将完美运行。

怎么了?

$address = $_GET['q']; // this GET can be spaced or not

这是一个 url,因此您必须在放入 youtube 查询之前进行编码

$address = urlencode($_GET['q']);

PHP urlencode