如何使用php curl从youtube URL中获取html


How to get html out of youtube URL using php curl?

我想获得Youtube URL(https)的源代码,它类似于我们在浏览器中看到的"查看页面源代码"选项。

以下是我的php代码-(index.php)

<?php
function gethtml($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    $ip=rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"));
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/".rand(3,5).".".rand(0,3)." (Windows NT ".rand(3,5).".".rand(0,2)."; rv:2.0.1) Gecko/20100101 Firefox/".rand(3,5).".0.1");
    $html = curl_exec($ch);
    curl_close($ch);
    return $html;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $url = $_REQUEST["url"];
    $html = gethtml($url);
    echo htmlspecialchars($html);
}
?>
<html>
    <head></head>
    <body>
        <form name="test" method="POST" action="./index.php"/>
            URL : <input type="text" name="url"/>
            <br>
            <input type="submit" value="See HTML" name="submit"/>
            <br>
        </form>
    </body>
</html>

它适用于其他URL,但不适用于任何youtube URL。为什么?

你可以试试这个:

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
var_dump(getSSLPage($_POST["url"]));
?>

如果你不坚持cURL,你可以使用:

file_get_contents();

这将以字符串形式返回url资源,因此:

echo file_get_contents('https://www.youtube.com/watch?v=fyLGa0E3OXk');

这将打印给定URL的来源。

由于标题的注释而编辑:

您可以将使用stream_context_create()创建的上下文资源传递给file_get_contents