如何在表中显示 json 输出


How to show json output in table

我编写了以下代码来调用 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 调用的输出?

首先,使用 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>";

请尝试"json_encode"以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 json_encode($result);
?>