用于xml的foreach循环

时间:2017-08-25 06:21:11

标签: php laravel

我在PHP代码中加载了xml;

<SiteAlarmDetails>
    <AlertId>89637</AlertId>
    <SiteCode>20157498</SiteCode>
    <SiteName>newport</SiteName>
</SiteAlarmDetails>



$alertXml = simplexml_load_string( $tableAlarm->AlarmDetails);

echo (string) $alertXml->AlertId;  //prints **89637**

现在我尝试遍历这个XML节点;

foreach($alertXml->children() as $alerts) 
{
   $alertId = (string)$alerts->AlertId;
   echo $alertId;//I do not see anything
}

在foreach循环中是否正确的方法来遍历AlertId?

1 个答案:

答案 0 :(得分:3)

尝试简单的foreach会很有帮助。只是为了访问单个值(例如AlertId),您可以使用$alertXml->AlertId;

Try this code snippet here

<?php
ini_set('display_errors', 1);
$xmlString=<<<XML
<SiteAlarmDetails>
    <AlertId>89637</AlertId>
    <SiteCode>20157498</SiteCode>
    <SiteName>newport</SiteName>
</SiteAlarmDetails>
XML;


$alertXml = simplexml_load_string( $xmlString);
foreach($alertXml as $key => $child)
{
    echo $key ."=".(string)$alertXml->{$key};
    echo PHP_EOL;
}

<强>输出:

AlertId=89637
SiteCode=20157498
SiteName=newport