tags:

views:

240

answers:

2

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.

+1  A: 

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";
}
Kerry
Thanks a lot guys , it worked just fine.You guys rock,Thanks once again...
Aditya
A: 

If the object that you print_r-ed in the question is in $element then the following will loop over the two time-entry elements while printing out their respective description and hours values.

foreach ($element->{'time-entry'} as $entry) {
    $description = (string) $entry->description;
    $hours       = (string) $entry->hours;
    printf("Description: %s\nHours: %s\n\n", $description, $hours);
}

Outputs something like:

Description: TCDM1 data management: sort & upload NFP SubProducers list
Hours: 1.0

Description: PDCH1: HTML
Hours: 0.25

Note that the time-entry element name has to be wrapped in curly braces1 as a string since otherwise $element->time-entry would try to read the time element and subtract the value of a constant called entry which is obviously not what we want. Also, the description and hours values are cast2 to strings (they would otherwise be objects of type SimpleXMLElement).

1. See variable variables 2. See type casting

salathe
Thanks a lot guys , it worked just fine. You guys rock, Thanks once again..
Aditya