一:获取http网页源代码:

      函数:file_get_contents()

        源代码如下:

<?php
header("Content-Type: text/html;charset=utf-8");
$url = 'http://www.dilidili.wang/';
$str = file_get_contents($url);//获取网页,此时输出$str为解析版网页
$str = htmlspecialchars($str);//转换为源代码
echo $str;
?>

二:获取https网页源代码:

         若用file_get_contents()函数会报错: 

file_get_contents(): Unable to find the wrapper "https" - did you forget to enable it when you configured PHP

所以用函数:curl_setopt()

代码如下:

<?php 
header("Content-Type: text/html;charset=utf-8");

function getHttps($url){    
   //初始化
        $ch = curl_init();
        //设置选项,包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        
        $output = curl_exec($ch); //执行并获取HTML文档内容
        $str = htmlspecialchars($output);//转换为源代码形式
        //释放curl句柄
        curl_close($ch);
    return  $str ;
	}
	
$url ='https://www.hao123/index.html'; 
echo getHttps($url);
?>

 

最后备注:

很多文章都是直接输出解析后的网页,而我想要源代码。只需加上htmlspecialchars()函数即可!

 

 

更多推荐

php获取http和https网页源代码