如何在表中显示json输出

时间:2016-02-09 06:14:32

标签: php html json

我编写了以下代码来调用json并显示输出。

`

$data = array("user" => "$username", "pass" => "$password", "msisdn" => "$msisdn", "receiver_msisdn" => "", "trx_type" => "", "from_date" => "$startdate", "to_date" => "$enddate");
$data_string = json_encode($data);

$ch = curl_init('http://ip:port/call_center/account/statementsearch');
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',
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;


    ?>

现在如何在表格中显示json调用的输出?

2 个答案:

答案 0 :(得分:1)

首先,使用json_decode()函数解码json字符串,并在该函数中将assoc参数设置为TRUE,以将对象转换为关联数组。然后循环遍历数组以将其显示在表中,如下所示:

// your code

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

$arr = json_decode($result, true);

echo "<table>";
foreach($arr['transactions'] as $a){
    foreach($a as $key => $value){
        echo "<tr><td>" . $key . "</td><td>" . $value . "</td></tr>";
    }
}
echo "</table>";

答案 1 :(得分:0)

请在json中尝试使用“json_encode”返回数据。

$data = array("user" => "$username", "pass" => "$password", "msisdn" => "$msisdn", "receiver_msisdn" => "", "trx_type" => "", "from_date" => "$startdate", "to_date" => "$enddate");
$data_string = json_encode($data);

$ch = curl_init('http://ip:port/call_center/account/statementsearch');
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',
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo json_encode($result);
?>