【发布时间】:2020-12-21 21:43:51
【问题描述】:
我正在尝试找出一种将 XML 文件中的数据解析为表的方法。问题是,如果 XML 字段中的 ChargeType 不一致,我将无法在表格中正确显示它。
这是 XML:
<ItemTaxWithheldList>
<TaxWithheldComponent>
<TaxesWithheld>
<ChargeComponent>
<ChargeType>MarketplaceFacilitatorTax-Shipping</ChargeType>
<ChargeAmount>
<CurrencyAmount>-5.54</CurrencyAmount>
</ChargeAmount>
</ChargeComponent>
<ChargeComponent>
<ChargeType>MarketplaceFacilitatorTax-Principal</ChargeType>
<ChargeAmount>
<CurrencyAmount>-10.87</CurrencyAmount>
</ChargeAmount>
</ChargeComponent>
</TaxesWithheld>
</TaxWithheldComponent>
<TaxWithheldComponent>
<TaxesWithheld>
<ChargeComponent>
<ChargeType>MarketplaceFacilitatorTax-Other</ChargeType>
<ChargeAmount>
<CurrencyAmount>-0.27</CurrencyAmount>
</ChargeAmount>
</ChargeComponent>
<ChargeComponent>
<ChargeType>MarketplaceFacilitatorTax-Shipping</ChargeType>
<ChargeAmount>
<CurrencyAmount>0.0</CurrencyAmount>
</ChargeAmount>
</ChargeComponent>
<ChargeComponent>
<ChargeType>MarketplaceFacilitatorTax-Principal</ChargeType>
<ChargeAmount>
<CurrencyAmount>0.0</CurrencyAmount>
</ChargeAmount>
</ChargeComponent>
</TaxesWithheld>
</TaxWithheldComponent>
<TaxWithheldComponent>
<TaxesWithheld>
<ChargeComponent>
<ChargeType>MarketplaceFacilitatorTax-Shipping</ChargeType>
<ChargeAmount>
<CurrencyAmount>0.0</CurrencyAmount>
</ChargeAmount>
</ChargeComponent>
<ChargeComponent>
<ChargeType>MarketplaceFacilitatorTax-Principal</ChargeType>
<ChargeAmount>
<CurrencyAmount>-4.87</CurrencyAmount>
</ChargeAmount>
</ChargeComponent>
</TaxesWithheld>
</TaxWithheldComponent>
</ItemTaxWithheldList>
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<table style="width:100%">
<tr>
<th>MarketplaceFacilitatorTax-Other</th>
<th>MarketplaceFacilitatorTax-Shipping</th>
<th>MarketplaceFacilitatorTax-Principal</th>
</tr>
<?php
$response = $xmlFile;
$return_data = simplexml_load_string($response);
$array = json_decode(json_encode((array)$return_data), TRUE);
foreach ($array['TaxWithheldComponent'] as $itemTaxWithheldList) {
echo '<tr>';
foreach ($itemTaxWithheldList['TaxesWithheld']['ChargeComponent'] as $key) {
$mpftChargeType = $key['ChargeType'];
$mpftChargeAmount = number_format((float)$key['ChargeAmount']['CurrencyAmount'], 2, '.', '');
if ($mpftChargeType == 'MarketplaceFacilitatorTax-Other') {
echo '<td>' . $mpftChargeAmount . '</td>';
} else {
echo '<td>0.00</td>';
}
if ($mpftChargeType == 'MarketplaceFacilitatorTax-Shipping') {
echo '<td>' . $mpftChargeAmount . '</td>';
} else {
echo '<td>0.00</td>';
}
if ($mpftChargeType == 'MarketplaceFacilitatorTax-Principal') {
echo '<td>' . $mpftChargeAmount . '</td>';
} else {
echo '<td>0.00</td>';
}
}
echo '</tr>';
}
?>
</table></body></html>
如果有人能指出我正确的方向,我将不胜感激。
【问题讨论】:
标签: php arrays xml-parsing