php curl獲取數(shù)據(jù)的方法:1、通過“function http_curl($url, $type = 'get', $data = ''){...}”方法獲取數(shù)據(jù);2、分別用POST和GET獲取數(shù)據(jù)即可。
本文操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
php curl 怎么只獲取數(shù)據(jù)?
php 使用 CURL 獲取數(shù)據(jù)
?第一種,POST 和 GET 合并
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
function http_curl($url, $type = 'get', $data = ''){ $cl = curl_init(); //初始化 curl_setopt($cl, CURLOPT_URL, $url); //設(shè)置 cURL 傳輸選項(xiàng) curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1); // 將curl_exec()獲取的信息以字符串返回,而不是直接輸出。 curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false); if($type == 'post'){ curl_setopt($cl, CURLOPT_POST, 1); //發(fā)送 POST 請求,類型為:application/x-www-form-urlencoded curl_setopt($cl, CURLOPT_POSTFIELDS, $data); } $output = curl_exec($cl); //執(zhí)行 cURL 會(huì)話 curl_close($cl); return $output; }
第二種 POST 和 GET分開
POST
$url = "http://localhost/web_services.php"; $post_data = array ("username" => "bob","key" => "12345"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // post數(shù)據(jù) curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // post的變量 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); $output = curl_exec($ch); curl_close($ch); //打印獲得的數(shù)據(jù) print_r($output);
GET
//初始化 $ch = curl_init(); //設(shè)置選項(xiàng),包括URL curl_setopt($ch, CURLOPT_URL, "http://www.jb51.net"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //執(zhí)行并獲取HTML文檔內(nèi)容 $output = curl_exec($ch); //釋放curl句柄 curl_close($ch); //打印獲得的數(shù)據(jù) print_r($output);
以上方式獲取到的數(shù)據(jù)是json格式的
使用? json_decode($output,true)可解析為數(shù)組;使用 json_decode($output) 可解析為對象
參數(shù)說明:
$url :要請求的url地址,如果是get方式請求,可以把參數(shù)直接加到url后面
$type:請求方式
$data:post方式請求時(shí)攜帶的參數(shù)
curl_init() 初始化一個(gè)cURL會(huì)話
curl_setopt() 設(shè)置一個(gè)cURL傳輸選項(xiàng)
curl_exec() 執(zhí)行一個(gè)cURL會(huì)話
curl_close() 關(guān)閉一個(gè)cURL會(huì)話
推薦學(xué)習(xí):《PHP視頻教程》
以上就是php curl 怎么只獲取數(shù)據(jù)的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
PHP怎么學(xué)習(xí)?PHP怎么入門?PHP在哪學(xué)?PHP怎么學(xué)才快?不用擔(dān)心,這里為大家提供了PHP速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號