使用PHP从XML显示属性

时间:2011-01-02 17:42:35

标签: php xml

我需要从以下XML文件中显示CD的id属性。除了id之外,我正确显示所有内容。

显示代码

<?php
    $doc = new DOMDocument();
    $doc->load( 'insert.xml' );

    $CATEGORIES = $doc->getElementsByTagName( "CD" );

    foreach( $CATEGORIES as $CD )
    {
        $TITLES = $CD->getElementsByTagName( "TITLE" );
        $TITLE = $TITLES->item(0)->nodeValue;

        $BANDS= $CD->getElementsByTagName( "BAND" );
        $BAND= $BANDS->item(0)->nodeValue;

        $YEARS = $CD->getElementsByTagName( "YEAR" );
        $YEAR = $YEARS->item(0)->nodeValue;

        echo "<b>$TITLE - $BAND - $YEAR\n</b><br>";
    }
?>

XML

<?xml version="1.0" encoding="utf-8"?>
<MY_CD>
    <CATEGORIES>
        <CD id="3231">
            <TITLE>NEVER MIND THE BOLLOCKS</TITLE>
            <BAND>SEX PISTOLS</BAND>
            <YEAR>1977</YEAR>
        </CD>
        <CD id="2453">
            <TITLE>NEVERMIND</TITLE>
            <BAND>NIRVANA</BAND>
            <YEAR>1991</YEAR>
        </CD>
    </CATEGORIES>
</MY_CD>

2 个答案:

答案 0 :(得分:2)

使用DOMElement::getAttribute

$id = $CD->getAttribute('id');

答案 1 :(得分:1)

我建议使用SimpleXML,它易于管理,更适合您的示例。属性可以这样访问:

$id = $CD['id'];