使用 CURL 将数组从一页转移到另一页

Transfer array from one page to another using CURL

我正在尝试在两个文件之间传输一组数据。

sender.php代码(文件发送数组使用POST方法)

$url = 'http://localhost/receiver.php';
$myvars = array("one","two","three")
$post_elements = array('myvars'=>$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_elements);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

echo "$response";

receiver.php代码(文件从sender.php文件接收数组,然后获取数组的每个元素并回显并放入在文档中 saved.txt.

    echo $_POST($myvars); // To test the output of the received data.

      foreach($myvars as $item) {
       if (!empty($item)) {
        echo $item."<br>";
$myfile = file_put_contents('Saved.txt', (" Name: ". ($_POST["$item"])) . PHP_EOL , FILE_APPEND);
      }
    }

数组没有传输到 receiver.php 或者我没有捕捉到它。在文档输出中,我只在变量 $item 的位置而不是数组的每个元素。

编辑: 为了从内部获取数组元素,在接收文件中添加了以下代码,但我得到的只是打印出来的数组:

foreach( $_POST as $stuff ) {
    if( is_array( $stuff ) ) {
        foreach( $stuff as $thing ) {
            echo $thing;
        }
    } else {
        echo $stuff;
    }
}

通过在接收文件中添加以下内容:

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

我得到以下信息:

Array
(
    [myvars] => Array
)

尝试序列化数组,因为它总是对我有帮助:

$url = 'http://localhost/receiver.php';
$myvars = array("one","two","three");
$myvars_post=join(" ",$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, "array=".urldecode($myvars_post));
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

echo "$response";

并在 receiver.php 中使用:

print_r($_POST);

OK,上面评论的讨论底线导致了这个结果:

发送部分:

<?php
$url = 'http://localhost/out.php';
$myvars = array("one","two","three");
$post_elements = array('myvars'=>$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($post_elements));
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
print_r($response);

接收部分:

<?php
print_r($_POST);

发送方的输出是:

Array ( [myvars] => Array ( [0] => one [1] => two [2] => three ) )

这基本上是说您可以简单地在接收端使用 $_POST['myvars'],它将准确保存您要传输的标量数组。