如何使用cURL和PHP从其他网站获取特定数据? 这是我的代码:
$page = curl_init('http://lookup.cla.base8tech.com/');
$encoded ='';
foreach($_GET as $name=>$value){
$encoded .= urlencode($name) .'=' .urlencode($value).'&';
}
foreach ($_POST as $name=>$value){
$encoded .= urlencode($name) .'=' .urlencode($value).'&';
}
preg_match('!\d+!', $encoded, $zip);
print_r($zip);
$encoded = substr($encoded, 0, strlen($encoded)-1 );
curl_setopt($page, CURLOPT_POSTFIELDS, $encoded);
curl_setopt($page, CURLOPT_HEADER, 0);
curl_setopt($page, CURLOPT_POST, 1 );
curl_exec($page);
curl_close($page);
答案 0 :(得分:0)
我发现代码中有一些错误。首先,要解决您的主要问题,您的cURL
请求并未正确执行。要使用POST
发送cURL
请求并检索响应,请使用以下代码:
$ch = curl_init($url); // Set cURL url
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // Send request via POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Set POST data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // curl_exec() returns response
curl_setopt($ch, CURLOPT_HEADER, "Content-Type: application/x-www-form-urlencoded");
$response = curl_exec($ch); // Return the request response
curl_close($ch);
此外,在您的代码中,您使用$encoded = substr($encoded, 0, strlen($encoded)-1 );
。这不是必需的,只需执行$encoded = substr($encoded, 0, -1 );
。
第三,您的正则表达式目前无效。您需要在字符串的开头和结尾添加/
:preg_match('/!\d+!/', $encoded, $zip);
最后,您的foreach
循环并非完全必要。您可以改为使用http_build_query
功能:$encoded = http_build_query($_GET) . "&" . http_build_query($_POST);
。这也使您的substr
行毫无意义。
因此,您需要以下内容:
$encoded = "";
// Check to make sure the variables encoded are actually set
if(!empty($_POST) && !empty($_GET)) {
$encoded = http_build_query($_GET) . "&" . http_build_query($_POST);
} elseif (empty($_POST) && !empty($_GET)) {
$encoded = http_build_query($_GET);
} elseif (!empty($_POST) && empty($_GET)) {
$encoded = http_build_query($_POST);
} else {
$encoded = "";
}
$encoded = http_build_query($_GET) . "&" . http_build_query($_POST);
preg_match('/!\d+!/', $encoded, $zip);
print_r($zip);
$ch = curl_init("http://lookup.cla.base8tech.com/"); // Set cURL url
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // Send request via POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded); // Set POST data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // curl_exec() returns response
curl_setopt($ch, CURLOPT_HEADER, "Content-Type: application/x-www-form-urlencoded");
$response = curl_exec($ch); // Return the request response
curl_close($ch);