【phpstudy】php curl file_get_contents post方式获取数据

更新时间:2020-11-26    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】

curl post,file_get_contents post,curl file_get_contents post请求数据

在PHP中cURL、file_get_contents函数均可以获取远程链接的数据,但是file_get_contents的可控制性不太好,对于各种复杂情况的数据采集情景,file_get_contents显得有点无能为力,cURL在数据采集情景复杂的环境下略显优势。cURL函数的curl_setopt里面还有很多参数,读者可以抽空整体看一遍,虽然平时未必用得上,但是至少做到心里有底,知道都有哪些参数,必要时还能找出来使用。本文仅粗略介绍了file_get_contents函数和cURL函数的基本使用:

curl post方式获取数据
//调用示例
$post_data = array ("category" => "9");
echo postCurl("http://fity.cn/category.php",$post_data);

//CURL函数--POST方式请求资源
function postCurl($api_url, $post_data){
    $ch = curl_init(); // 初始化CURL句柄
    curl_setopt($ch, CURLOPT_URL, $api_url); // 设置访问的url地址
    curl_setopt($ch, CURLOPT_TIMEOUT, 35); // 设置超时
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); // 等待的时间,如果设置为0,则不等待
    curl_setopt($ch, CURLOPT_HEADER, false); // 设定是否输出页面内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 设定是否显示头信息
    curl_setopt($ch, CURLOPT_POST, true);  // post数据
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);// post的变量
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); // 模拟浏览器头信息
    curl_setopt($ch, CURLOPT_REFERER, "http://www.x.com"); // 伪造来源地址
    $data = curl_exec($ch);
    curl_close($ch);
  if ($data) {
    return $data;
  } else {
    return false;
  }
}
file_get_contents post方式获取数据
$postdata = array ("category" => 9);
$postdata = http_build_query($postdata);
$opts = array (
  "http" => array (
  "method" => "POST",
  "content" => $postdata
)
);
$context = stream_context_create($opts);
$html = file_get_contents("http://fity.cn/category.php", false, $context);
echo $html;

本文来源:http://www.bbyears.com/jiaocheng/112748.html