如何使用PHP获取XML属性

时间:2017-11-01 11:50:51

标签: php xml

这是我的xml文件:

<device name=" name ">
<interface>
    <ip > someip </ip>
</interface>
<display>
    <name> \\.\DISPLAY1 ( 1920 X 1080 )</name>
</display>
<output>
    <audio> Speakers (High Definition Audio </audio>
    <audio> Digital Audio (S/PDIF) (High De </audio>
    <audio> Digital Audio (S/PDIF) (High De </audio>
</output>

这是我的PHP代码:

<body style="font-family: Arial">
<?php
    $xml=simplexml_load_file("device.xml");
    var_dump($xml);
    $attr = $xml->device->attributes()->name;
?>
<div id="leftDiv">
    <ul id="menu">
        <li><?php echo $attr; ?></li>
    </ul>
</div>
<div id="mainDiv">

</div>
<div id="rightDiv">

</div>

我想访问设备的名称属性并获取其值,但我总是收到错误:main():第30行的C:\ xampp \ htdocs \ Project \ index.php中不再存在节点第30行是这一行:$ attr = $ xml-&gt; device-&gt; attributes() - &gt; name;怎么了?

1 个答案:

答案 0 :(得分:1)

php文件代码

device

中删除$xml->device->attributes()->name;
<body style="font-family: Arial">
<?php
    $xml=simplexml_load_file("device.xml");
    var_dump($xml);
    $attr = $xml->attributes()->name;
?>
<div id="leftDiv">
    <ul id="menu">
        <li><?php echo $attr; ?></li>
    </ul>
</div>
<div id="mainDiv">

</div>
<div id="rightDiv">

</div>

xml文件

错过</device>到文件结尾,所以把它放在

<device name=" name ">
<interface>
    <ip > someip </ip>
</interface>
<display>
    <name> \\.\DISPLAY1 ( 1920 X 1080 )</name>
</display>
<output>
    <audio> Speakers (High Definition Audio </audio>
    <audio> Digital Audio (S/PDIF) (High De </audio>
    <audio> Digital Audio (S/PDIF) (High De </audio>
</output>
</device>