1

我正在从此 XML 文件中获取 sky_condition 的 XML 属性:

<METAR>  
    <sky_condition sky_cover="SCT" cloud_base_ft_agl="1600"/>
    <sky_condition sky_cover="BKN" cloud_base_ft_agl="2200"/>
</METAR>

使用 PHP 代码:

$sky  = $xml->data->METAR[0]->sky_condition->attributes();

(我删除了额外的 XML 代码)

我用它来输出数据:

<table border="0">
            <?php foreach ($sky as $sky_cover => $cloud_base_ft_agl){
            echo"<tr>";
            echo"<td><strong>";
            if ($sky_cover == "CAVOK") {echo "Ceiling and Visibility OK";} else {echo $sky_cover;
            }
            echo"</strong></td>";
            echo"<td><strong>";
            if (isset($cloud_base_ft_agl)){echo $cloud_base_ft_agl; }
            echo"</strong></td>";
            echo"</tr>";
        }?>
        </table>

无论如何我可以显示数据,例如:

<table>
  <tr>
    <td><strong>SCT</strong></td>
    <td><strong>1600</strong></td>
  </tr>
  <tr>
    <td><strong>BKN</strong></td>
    <td><strong>2200</strong></td>
  </tr>
</table>
4

1 回答 1

1

就这样做

$xmlString = '<METAR>
   <sky_condition sky_cover="SCT" cloud_base_ft_agl="1600"/>
    <sky_condition sky_cover="BKN" cloud_base_ft_agl="2200"/>
</METAR>
';

$xml = simplexml_load_string($xmlString);
$td = "<tr><td><strong>%s</strong></td><td><strong>%s</strong></td></tr>";
echo '<table>';

foreach ( $xml->sky_condition as $value ) {
    $attribute = $value->attributes();
    printf($td, $attribute['sky_cover'], $attribute['cloud_base_ft_agl']);
}

echo '</table>';

看演示

http://codepad.viper-7.com/A9pba4

于 2012-08-24T20:39:20.153 回答