0

I have a curl function to call a service that return output like this

[{"idpacket":1,"packetname":"Silver","packetdesc":"Silver is da best","packetprize":"Rp 20000","packettime":"365 days"}]

I wanna echo all of element into table row

How i do that? I always get error on foreach function. Please help

This is my code:

<?php
//step1
$cSession = curl_init(); 
//step2
curl_setopt($cSession,CURLOPT_URL,"http://localhost:8080/packet");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false); 
//step3
$result=curl_exec($cSession);
//step4
curl_close($cSession);
//
foreach ((array) $result as $item) {
print_r($item['idpacket']);
 }
?>

Thank you :)

Rakesh Soni
  • 1,293
  • 2
  • 11
  • 27
dedypuji
  • 105
  • 1
  • 3
  • 12

2 Answers2

1

I got this conclusion as I understood

write this code and check :

print_r((array)$result);

its place your JSON into an array does not decode your JSON like this:

Array
(
    [0] => [{"idpacket":1,"packetname":"Silver","packetdesc":"Silver is da best","packetprize":"Rp 20000","packettime":"365 days"}]
)

if you want to access 'idpacket'

write like this:

$result_array = json_decode($result,true);

foreach ((array) $result_array as $item) {
      print_r($item['idpacket']);
}
Nidhi
  • 1,529
  • 18
  • 28
  • thanks it's work like what i want. if i may know,, the curl result json, is that a json or what ? how come we must decode again in variable result array. i dont understand. but thanks anyway :) – dedypuji May 15 '17 at 09:24
0

You could write something like

<?php
$resultArr = json_decode($result,true);

$header="<tr>";
$row="<tr>";
echo "<table>";

foreach($resultArr[0] as $col => $val)
{
  $header.="<td>".$col."</td>";
  $row.="<td>".$val."</td>";
}

$header.="</tr>";
$row.="</tr>";

echo $header;
echo $row;
echo "</table>";

?>
Code3d
  • 73
  • 5