Search code examples
phpparsingsimplexml

How to get attribute in tag using SimpleXML


I'm not sure of how to call what I want, so if you can provide any more accurate term, I'll update my question.

I'd like to get data from an XML site structured like this:

<body>
    <predictions>
        <message text="message"/>
    </predictions>
    <predictions>
        <direction title="Dir1">
            <prediction epochTime="1521560640000" seconds="724" minutes="12" isDeparture="true" affectedByLayover="true" dirTag="paciland" vehicle="1606" block="22"/>
        </direction>
    </predictions>
</body>

I'd like to get the seconds (or minutes...) value.

I've found information about getting data from something structured like this:

<body>
    <predictions>
        <message text="message"/>
    </predictions>
    <predictions>
        <direction title="Dir1">
            <prediction>
                epochTime="1521560640000"
                seconds="724" 
                minutes="12" 
                isDeparture="true" 
                affectedByLayover="true" 
                dirTag="paciland" 
                vehicle="1606" 
                block="22"
            </prediction>
        </direction>
    </predictions>
</body>

Where data are not in the tag.

I've never used SimpleXML so I'm a bit confused about how to get that.


Solution

  • Accessing attributes with simpleXML can be done using $element['attribute_name'].

    Here is an example to get the seconds attribute from a <prediction> tag.

    $xml = '<body>
        <predictions>
            <message text="message"/>
        </predictions>
        <predictions>
            <direction title="Dir1">
                <prediction epochTime="1521560640000" seconds="724" minutes="12" isDeparture="true" affectedByLayover="true" dirTag="paciland" vehicle="1606" block="22"/>
            </direction>
        </predictions>
    </body>';
    
    $xmlobj = simplexml_load_string($xml);
    foreach ($xmlobj->predictions as $prediction) {
        if (isset($prediction->direction)) {
            echo $prediction->direction->prediction['minutes'];
            echo $prediction->direction->prediction['seconds'];
        }
    }