Php 如何从其他网站获取数据
如何使用cURL和PHP从另一个网站获取特定数据? 这是我的代码:Php 如何从其他网站获取数据,php,curl,Php,Curl,如何使用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){
$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);
我注意到你的代码中有几个错误。首先,为了解决您的主要问题,您的cURL请求没有完全正确。要使用cURL发送POST请求并检索响应,请使用以下代码:
$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+!/'$编码$zip
最后,您的foreach循环并非完全必要。您可以使用http\u build\u query函数:$encoded=http\u build\u query$\u GET.&。http\u build\u query$\u 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);