Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through a SimpleXML object in PHP

Tags:

php

simplexml

I have a simpleXml object and want to read the data from the object , I am new to PHP and dont quite know how to do this. The object details are as follows.

I need to read [description] and [hours]. Thankyou.

SimpleXMLElement Object (
    [@attributes] => Array (
        [type] => array
    )
    [time-entry] => Array (
        [0] => SimpleXMLElement Object (
            [date] => 2010-01-26
            [description] => TCDM1 data management: sort & upload
            [hours] => 1.0
            [id] => 21753865
            [person-id] => 350501
            [project-id] => 4287373
            [todo-item-id] => SimpleXMLElement Object (
                [@attributes] => Array (
                    [type] => integer
                    [nil] => true
                )
            )
        )
        [1] => SimpleXMLElement Object (
            [date] => 2010-01-27
            [description] => PDCH1: HTML
            [hours] => 0.25
            [id] => 21782012
            [person-id] => 1828493
            [project-id] => 4249185
            [todo-item-id] => SimpleXMLElement Object (
                [@attributes] => Array (
                    [type] => integer
                    [nil] => true
                )
            )
)   )   )

Please help me. I tries a lot of stuff , but not getting the syntax right.

like image 417
Aditya Avatar asked May 24 '10 21:05

Aditya


1 Answers

It's really hard to read the above, if you could give us a screen shot or give line spacing and indents, that would be a bit better If you have an object

$xml that is a simplexml object, you can access elements like

$xml->element.

It looks like is an element of time entry, in which case you would loop through like this:

foreach( $xml->{'time-entry'} as $time_entry ) {
    echo $time_entry->description . "<br />\n";
}
like image 158
Kerry Jones Avatar answered Sep 22 '22 10:09

Kerry Jones