Search code examples
phpsimplexml

iterate through SimpleXMLElement Object in php


I can't iterate through this xml file. I'm using simplexml_load_file(). does anyone have a solution? Thanks for your time. I'm a newbie!

SimpleXMLElement Object
(
[ReferenceMember] => SimpleXMLElement Object
    (
        [Agency] => SimpleXMLElement Object
            (
                [ID] => xx
                [ActivityID] => xxxxx
                [ActivityReferenceID] => xxxxx
            )

    )

[Member] => SimpleXMLElement Object
    (
        [Agency] => SimpleXMLElement Object
            (
                [ID] => xx
                [ActivityID] => xxxx
                [ActivityReferenceID] => xxxx
            )

    )

[SubmissionID] => xxxx
[Company] => xxxxx

[Emails] => SimpleXMLElement Object
    (
        [Email1] => [email protected]
    )

[UploadedDate] => 24/11/14
)

this is what I've tried

$data = simplexml_load_file($file);

foreach ($data as $item) {

        foreach ($item->item as $entry) {
            $this->set_date($entry->UploadedDate);

        }

}

$array = array(
            "DATE" => $this->get_date()

        );

var_dump($array);

this is what i get

array(1) {
  ["DATE"]=>
  NULL
}

when i try to acces object value

var_dump($date->UploadedDate);

object(SimpleXMLElement)#9 (1) {
  [0]=>
  string(8) "24/11/14"
}

Solution

  • According to the information you've given us, you don't need to loop at all, because you only want one answer, and you know exactly where to find it:

    $data = simplexml_load_file($file);
    $this->set_date( (string)$data->UploadedDate );
    

    Note that I've used (string) here; this removes the SimpleXML magic from the found value, which will probably be what you want later. echo does this for you, so echo $data->UploadedDate; would show what you expect.