LittleBigDev
LittleBigDev

Reputation: 484

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 ?

Upvotes: -1

Views: 549

Answers (2)

IMSoP
IMSoP

Reputation: 97987

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(); 
 }

Upvotes: 0

metalfight - user868766
metalfight - user868766

Reputation: 2750

You can use Xpath.

Please try below code, i have tested it with both of sample XML's you provided.

<?php

$subscriptions = simplexml_load_file('test.xml');

$scTag = $subscriptions->xpath("//subscription");

 foreach($scTag as $subscription) {
     echo $subscription->eventName;
          /* using $subscription->eventName etc... */
 } 
?>

hope this help !

Upvotes: 1

Related Questions