I try to check if SimpleXml element is an array.
I saw the given examples here on PHP doc and so it seems possible to check if a node is an array. But in my case, I cannot do it.
A var_dump($myElement)
gives me:
object(SimpleXMLElement)#701 (4) {
["@attributes"]=> array(1) {
["id"]=> string(7) "5831377"
}
["openPeriod"]=> string(10) "2016-04-01"
["closePeriod"]=> string(10) "2016-05-31"
["periods"]=> object(SimpleXMLElement)#703 (1) {
["period"]=> array(2) {
[0]=> object(SimpleXMLElement)#707 (3) {
["startPeriod"]=> string(8) "10:00:00"
["endPeriod"]=> string(8) "12:30:00"
["weekDays"]=> string(51) "monday,tuesday,wednesday,thursday,friday,saturday,sunday"
}
[1]=> object(SimpleXMLElement)#702 (3) {
["startPeriod"]=> string(8) "14:00:00"
["endPeriod"]=> string(8) "20:00:00"
["weekDays"]=> string(51) "monday,tuesday,wednesday,thursday,friday,saturday,sunday"
}
}
}
}
Depending $myElement
, $myElement->periods->period
could be an object or an array.
But in the given case, debug(is_array($myElement->periods->period))
returns false
.
Could you tell me why?
EDIT
Here is the original XML element:
<openingPeriod id="5831487">
<openPeriod>2016-04-01</openPeriod>
<closePeriod>2016-05-31</closePeriod>
<periods>
<period>
<startPeriod>10:00:00</startPeriod>
<endPeriod>12:30:00</endPeriod>
<weekDays>monday,tuesday,wednesday,thursday,friday,saturday,sunday</weekDays>
</period>
<period>
<startPeriod>14:00:00</startPeriod>
<endPeriod>20:00:00</endPeriod>
<weekDays>monday,tuesday,wednesday,thursday,friday,saturday,sunday</weekDays>
</period>
</periods>
</openingPeriod>
Your underlying assumption is wrong:
Depending $myElement, $myElement->periods->period could be an object or an array.
The result of the ->
operator on a SimpleXMLElement object is always another SimpleXMLElement object. I'm not sure why there's so many mentions of is_array
in the comments of the page you linked to, but I think they're all just making the same mistake. You may be fooled by var_dump
or print_r
telling you there's an array, but it's lying; that's just how the debug info displays multiple items with the same name.
You can access the object as though it was an array, using [0]
, foreach
, etc, but these are all just convenience features of the object, not an actual array.
If you look at the official examples, you'll see that $myElement->periods->period
is just short-hand for $myElement->periods[0]->period
. So in most cases, you simply don't need to know if there are multiple children or just one, if you do foreach($myElement->periods->period as $period)
for instance, the loop will always work. SimpleXML takes care of the different scenarios for you.
If what you really want to know is how many of a particular element there are, you can use count($myElement->periods->period)
. But again, you should not need to have any special cases in your code for when there's only one.