Search code examples
simplexmlzend-configzend-config-xml

SimpleXML (Zend_Config_Xml actually) and foreach : which tag am I iterating?


I'm implementing a little event manager in order to use the Observer pattern. To subscribe my observers to my events, I'm using the following xml file :

<?xml version="1.0" encoding="UTF-8"?>
<configData>
    <subscriptions>
        <subscription>
            <eventName>event_name</eventName>
            <class>My_Observer_Class</class>
            <function>myFunction</function>
        </subscription>
        <subscription>
            <eventName>other_event_name</eventName>
            <class>My_Observer_Otherclass</class>
            <function>myOtherFunction</function>
        </subscription>
    </subscriptions>
</configData>

I'm using a foreach to loop on the subscriptions :

foreach($subscriptions->subscription as $subscription) {
    /* using $subscription->eventName etc... */
}

And everything is ok, each $subscription item has it's eventName etc...

But here comes my problem :

<?xml version="1.0" encoding="UTF-8"?>
<configData>
    <subscriptions>
        <subscription>
            <eventName>event_name</eventName>
            <class>My_Observer_Class</class>
            <function>myFunction</function>
        </subscription>
    </subscriptions>
</configData>

Here I have only one <subscription> node. And my foreach loops on the subscription children ! To solve this problem, I'd like to know how I can check if the xml file contains several <subscription> tags, or just one...

Any help will be appreciated :)

Edit : Is there a way to use xpath with my Zend_Config_Xml object ?


Solution

  • Just to clarify, this is an issue with Zend_Config_XML which is not present in PHP's native SimpleXML.

    Given your second example as $xml, I can run the following and get the word 'subscription' as expected:

     $configData = simplexml_load_string($xml);
     foreach($configData->subscriptions->subscription as $subscription)
     {
         echo $subscription->getName(); 
     }