1

I need to display the id attribute of a CD from the following XML file. I display everything correctly except the id.

Display code

<?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 Answers 2

2

Use DOMElement::getAttribute:

$id = $CD->getAttribute('id');
Sign up to request clarification or add additional context in comments.

Comments

1

I would suggest to use SimpleXML, it's easy to manage and more suitable for your example. Attributes are accessible like this:

$id = $CD['id'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.