在php

时间:2015-06-08 13:33:33

标签: php arrays post curl

我收集了数据并创建了数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Martin
            [surname] => test
            [email] => martin@gmail.com
            [dob] => 2015-02-24
        )

    [1] => Array
        (
            [id] => 2
            [name] => Kary
            [surname] => paulman
            [email] => kary@gmail.com
            [dob] => 2015-06-26
        )

)

我在这个数组中有多条记录。

我想将数组中的每条记录发布到www.recieve.com,在那里它会传递“真实”的回复。如果帖子成功并且“假”'如果它失败了。

我研究了互联网,我甚至不知道从哪里开始。

到目前为止,我的代码看起来像这样(这只适用于数组)

$query = "SELECT * FROM applicants";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($result)){
$res[] = $row;
}

echo "<pre>"; print_r($res);   echo "</pre>";

I have tryed this and it is not working : 

//Build my array
$query = "SELECT * FROM applicants";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($result)){
$res[] = $row;
}

//URL to post to
$url = 'https://theurl.com?';

//url-ify the data for the POST
foreach($res as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

2 个答案:

答案 0 :(得分:1)

我可以看到您的cURL请求有两个问题:

  1. 您没有正确编码值以用于查询字符串
  2. $fields未定义。
  3. 您可以使用例如:

    来解决这个问题
    // make sure the values are encoded correctly:
    $fields_string = http_build_query($res);
    
    $ch = curl_init();
    
    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL, $url);
    
    // you need the count of your `$res` variable here:
    curl_setopt($ch,CURLOPT_POST, count($res));
    
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    
    //execute post
    $result = curl_exec($ch);
    
    //close connection
    curl_close($ch);
    

    另请注意,您不需要在网址末尾添加问号。我不知道这是否会导致问题,但您应该删除它:

    $url = 'https://theurl.com';
    

答案 1 :(得分:0)

使用Curl,像这样

$ch = curl_init();                    // initiate curl
$url = "http://www.somesite.com/curl_example.php"; // where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);  // tell curl you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the output in string format
$output = curl_exec ($ch); // execute

curl_close ($ch); // close curl handle

var_dump($output); // show output

?>

在:curl_setopt中使用您的数组($ ch,CURLOPT_POSTFIELDS