在PHP中将数据以数组形式提交

3

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

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,如果发布成功,则返回“true”响应,如果失败,则返回“false”。
我已经在互联网上进行了研究,但我甚至不知道从哪里开始。
到目前为止,我的代码看起来像这样(这只是针对数组):
$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);

5
使用cURL - D4V1D
如果您使用Composer或类似的工具,我会推荐Guzzle。但Curl也可以使用。 - Sander Visser
2个回答

1
我看到你的cURL请求存在两个问题:
  1. 你没有正确编码值以在查询字符串中使用
  2. $fields未定义。
你可以使用以下方法解决这些问题:
// 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末尾加上问号。我不知道这是否会引起问题,但您应该将其删除:
$url = 'https://theurl.com';

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 中使用您的数组


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接