iT邦幫忙

0

php curl 寫在同一個function但沒辦法同時兩次請求?

我把curl寫在一個function像這樣:

function httpRequest ($api, $data_string)
{
  $ch = curl_init($api);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  $result = curl_exec($ch);
  curl_close($ch);

  return json_decode($result);
}

然後我同一頁有兩隻請求

$api_a = 'a';
$api_b = 'b';

$get_a = array(
      "session" => $_SESSION['session']
    );
    $get_a_str = json_encode($get_a);
    $get_a = httpRequest($api_a, $get_a_str);
    
$get_b = array(
      "session" => $_SESSION['session']
    );
    $get_b_str = json_encode($get_b);
    $get_b = httpRequest($api_b, $get_b_str);

寫在同一頁:

  <?foreach ($get_a->dataA as $key) {?>
          <?=@$key->{'name'};?>
        <?}?>
  <?foreach ($get_b->dataB as $key) {?>
          <?=@$key->{'name'};?>
        <?}?>

為什麼這樣不行同時呢?
他只能請求其中一個,另一個會無效?(誰在最上面誰才能運行)

他會報錯:

Undefined variable: get_b
Trying to get property 'dataB' of non-object
Invalid argument supplied for foreach()

我只要把A刪掉就可以運行B
把B刪掉就可以運行A
怎麼樣能夠多個請求呢?我這樣寫不對...

請問妳只執行其中一個的話,成功顯示出來的結果,會顯示什麼?
妳試試看改成這樣:
$api_a = 'a';
$api_b = 'b';

$array_a = array(
"session" => $_SESSION['session']
);
$get_a_str = json_encode($array_a);
$get_a = httpRequest($api_a, $get_a_str);

$array_b = array(
"session" => $_SESSION['session']
);
$get_b_str = json_encode($array_b);
$get_b = httpRequest($api_b, $get_b_str);

以及:
<?foreach ($get_a->dataA as $value) {?>
<?=@$value->{'name'};?>
<?}?>
<?foreach ($get_b->dataB as $value) {?>
<?=@$value->{'name'};?>
<?}?>
$_SESSION定義?

1 個回答

0
weiclin
iT邦高手 4 級 ‧ 2018-04-07 19:26:51
最佳解答

程式:

function httpRequest ($api, $data_string)
{
    //....略
}

$api_a = 'https://jsonplaceholder.typicode.com/posts';
$api_b = 'https://jsonplaceholder.typicode.com/posts';

$get_a = array(
    "session" => "abc"
);
$get_a_str = json_encode($get_a);
$get_a = httpRequest($api_a, $get_a_str);

$get_b = array(
    "session" => "123"
);
$get_b_str = json_encode($get_b);
$get_b = httpRequest($api_b, $get_b_str);

print_r($get_a);
print_r($get_b);

結果:

$ php curl.php 
stdClass Object
(
    [session] => abc
    [id] => 101
)
stdClass Object
(
    [session] => 123
    [id] => 101
)

好好的啊...

我要發表回答

立即登入回答