SimpleXML converts the XML document into an object, like this:

* Elements - Are converted to single attributes of the SimpleXMLElement object. When there's more than one element on one level, they're placed inside an array

So if there are multiple elements, they are place inside an array, so I can use foreach to get each element.

But if there is only one element, I cannot use foreach, it is not an array.

foreach ($event_xml->events->event as $event)
         {
             $this_event_id = $event->event_id;
             $this_title = $event->title;
             $this_description = $event->description;

          ...... //dozens lines codes
         }

So what I have to do is

if (is_array($event_xml->events->event))
{
foreach ($event_xml->events->event as $event)
         {
             $this_event_id = $event->event_id;
             $this_title = $event->title;
             $this_description = $event->description;

          ...... //dozens lines codes
         }
}
else
{
$event=$event_xml->events->event as $event;

         $this_event_id = $event->event_id;
         $this_title = $event->title;
         $this_description = $event->description;

          ...... //dozens lines codes

}

There got be a clean and simple way to handle that element is one element or multiple elements.

What is your advice?

Thanks!

    Sorry. I got SimpleXML confused with php SoapClient.

    For simplexml it is always in array even only one element. But for SoapClient, I need to know if it is multiple elements or single element to see if the return is an array or not.

      Could you do a little if/else based on a call to [man]is_array/man?

        Write a Reply...