2016-12-05 62 views
-3

如何使用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

我注意到你的代码中有几个错误。首先,为了解决您的主要问题,您的请求并不完全适合您的请求。要使用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+!/', $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); 
相关问题