0

我正在尝试用 php 学习 curl。我知道可以使用 curl 使用 post 方法将值发送到另一个脚本。但是,如果我想要那样,在第一次发送该值之后执行并使用 post 方法再次返回 .... 是可能的。在我的两个脚本上:

索引.php

<?php
$url = 'http://localhost/curl/test.php';

$post_data = array(
  'first' => '1',
  'second' => '2',
  'third' => '3'
  );

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

$output = curl_exec($ch);

curl_close($ch);

print_r($output);
?>

test.php

<?php
$a = $_POST['first'];
$b = $_POST['second'];

$c = $a+$b;
$d = $b-$a;
$e = $a*$b;

$output =  array(
  'choose' => $c,
  'choose1' => $d,
  'choose2' => $e
  );

print_r($output);
?>

这里 index.php 通过 post 方法发送,我可以使用 $_POST['first'] 访问它。如果我想从这里 test.php 传输 $output 数组并可以从 index.php 以 $_POST['choose'] 的形式访问它们,这可能吗?

4

2 回答 2

3

来自的响应curl不会像$_POST在脚本加载时设置的那样自动填充超全局变量。

您需要自己解析 curl 响应。我建议您以 PHP 易于解析的格式返回它。例如,JSON使用json_decode().

例子

print_r()分别用以下代码替换您的。

测试.php

echo json_encode($output);

索引.php

$data = json_decode($output, true);
print_r($data);
于 2013-04-22T13:51:55.053 回答
1

而不是 print_r($output); 在 test.php 中创建一个函数模块来处理数据,并返回:

return $output;

index.php, $output = curl_exec($ch); 是正确的,您最终可以通过以下方式访问数据:

echo $output->choose;
echo $output->choose1;

或者像上面提到的 Jason 一样使用parse_str()or 。json_decode()

于 2013-04-22T13:59:47.913 回答