PHP中的单独XML属性 [英] Separate XML attributes in PHP

查看:109
本文介绍了PHP中的单独XML属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这个XML文件中获取了sky_condition的XML属性:

I'm getting the XML attributes for sky_condition from this XML file:

<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代码)

(I've removed extra XML code)

我正在使用它来输出数据:

And I'm using this to output the data:

<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>

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

Is there anyway I could have the data displayed such as:

<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>


推荐答案

只需这样做

$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

这篇关于PHP中的单独XML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆