通过php输出xml文件的某些字段


Output certain fields of the xml file via php

我在xml文件中从服务器提取bios设置,并希望使用php只显示该xml文件的2个字段。

这是我的xml文件(名为ndphlsv02.xml)

<?xml version="1.0" encoding="UTF-8"?>
<SystemConfiguration Model="PowerEdge R720" ServiceTag="xxxxxx" TimeStamp="Wed Aug 12 08:23:51 2015">
    <Component FQDD="LifecycleController.Embedded.1">
        <Attribute Name="LCAttributes.1#CollectSystemInventoryOnRestart">Enabled</Attribute>
        <Attribute Name="LCAttributes.1#PartConfigurationUpdate">Apply always</Attribute>
        <Attribute Name="LCAttributes.1#PartFirmwareUpdate">Match firmware of replaced part</Attribute>
    </Component>
    <Component FQDD="System.Embedded.1">
        <Attribute Name="LCD.1#Configuration">Service Tag</Attribute>
        <Attribute Name="ThermalConfig.1#CriticalEventGenerationInterval">30</Attribute>
        <Attribute Name="ThermalConfig.1#EventGenerationInterval">30</Attribute>
    </Component>
    <Component FQDD="iDRAC.Embedded.1">
        <Attribute Name="IPMILan.1#Enable">Enabled</Attribute>
        <Attribute Name="IPMILan.1#PrivLimit">Administrator</Attribute>
    </Component>
    <Component FQDD="RAID.Integrated.1-1">
        <Attribute Name="RAIDresetConfig">False</Attribute>
        <Attribute Name="RAIDforeignConfig">Ignore</Attribute>
        <Attribute Name="RAIDrekey">False</Attribute>
    </Component>
    <Component FQDD="RAID.Slot.4-1">
        <Attribute Name="RAIDresetConfig">False</Attribute>
        <Attribute Name="RAIDforeignConfig">Ignore</Attribute>
    </Component>
    <Component FQDD="BIOS.Setup.1-1">
        <Attribute Name="MemTest">Disabled</Attribute>
        <Attribute Name="MemOpMode">OptimizerMode</Attribute>
        <Attribute Name="NodeInterleave">Disabled</Attribute>
        <Attribute Name="AcPwrRcvry">Last</Attribute>
        <Attribute Name="AcPwrRcvryDelay">Immediate</Attribute>
        <Attribute Name="NumLock">On</Attribute>
        <Attribute Name="ReportKbdErr">Report</Attribute>
    </Component>
</SystemConfiguration>

这是我目前为止的php代码:

$xml = simplexml_load_file('ndphlsv02.xml') or die("Error: Cannot create object");
$power=$xml->Component[5]->Attribute[3];
$power_attr = $xml->Component[5]->Attribute[3]->attributes();
$status=$xml->Component[5]->Attribute[4];
$status_attr = $xml->Component[5]->Attribute[4]->attributes();
echo $power_attr .": ". $power."<br>";
echo $status_attr .": ". $status;

这工作得很好,但我将有大约100个xml文件从每个服务器提取,我注意到,我需要提取的和,可以在完全不同的地方。因此,这将不再工作:

Component[5]->Attribute[3]

是否有一种方法可以让我搜索所有xml文件,只输出"属性",其名称是"AcPwrRcvry"answers"acpwrrcvydelay"及其值?

谢谢。

轻松。

$xml = simplexml_load_file('ndphlsv02.xml') or die("Error: Cannot create object");
$xpath = $xml->xpath('/SystemConfiguration/Component/Attribute[@Name="AcPwrRcvry" or @Name="AcPwrRcvryDelay"]');
foreach ($xpath as $attribute) {
    echo $attribute->attributes()->Name . ': ' . $attribute . '<BR>';
}
输出:

AcPwrRcvry: Last
AcPwrRcvryDelay: Immediate

更多信息请参见xpath文档页