$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 = '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
好好的啊...